<?php
import("ORG.Util.Function");
import("@.Org.SystemTool");
import("@.Org.OrderTool");
import("@.Org.UserTool");
import("@.Org.Utils");
import("@.Org.Encryption");
import("@.Org.Page");

class OrderAction extends CommonAction {
	
	public function _initialize(){
		parent::_initialize();		
		$param           =    $this->_get('_URL_');
		$controller      =    $param[0];
		$action          =    $param[1];		
		//language
		$lang            =    L($action);  		
		$manage          =    L('manage');
		$this->assign("manage",$manage);
		$this->assign("current",$lang);
		$this->assign("lang",$lang);		
	}
	
	/**
	 * 单个订单
	 * 
	 */
	public function order(){		
		$order_id		=	intval($_REQUEST['order_id']);
		$OrderModel		=	new OrderModel();
		$UserModel		=	new UserModel();
		$CommonModel	=	new CommonModel();
		$order			=	null;
		
		
	    /* 根据订单id或订单号查询订单信息 */
	    if (isset($_REQUEST['order_id'])){
	        $order_id = intval($_REQUEST['order_id']);
	        $order = $OrderModel->get_order_info($order_id);
	    }
	    elseif (isset($_REQUEST['order_sn'])){
	        $order_sn = trim($_REQUEST['order_sn']);
	        $order = $OrderModel->order_info(0, $order_sn);
	    }
	    else{
	        /* 如果参数不存在，退出 */
	        die('invalid parameter');
	    }	
	    /* 如果订单不存在，退出 */
	    if (empty($order)){
	        die('order does not exist');
	    }

	    /* 如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
	    //$sql 	=	 "SELECT agency_id FROM " . 'ybr_admin_user' . " WHERE user_id = '1'";	    
	    $agency_id	=	M('admin_user')->where("user_id = '{$_SESSION['user_id']}'")->getField("agency_id");
	    
	    if ($agency_id > 0){
	        if ($order['agency_id'] != $agency_id){
	            //sys_msg($_LANG['priv_error']);
	            //$this->error("用户所在的办事处权限不对");
	        }
	    }
		
	    /* 取得用户名 */
	    if ($order['user_id'] > 0){
	        $user 					= 	user_info($order['user_id']);
	        if (!empty($user)){
	            $order['user_name'] = 	$user['user_name'];
	        }
	    }
   	
	    /* 取得所有办事处 */
	    $sql 		= 	"SELECT agency_id, agency_name FROM " . 'ybr_agency';
	    $agencyList	=	M()->query($sql);
	    $this->assign("agencyList",$agencyList);

	    /* 取得区域名 */
	    $sql 		= 	"SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
	                	"'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
	            		"FROM " . 'ybr_order_info' . " AS o " .
	                	"LEFT JOIN " . 'ybr_region' . " AS c ON o.country = c.region_id " .
	                	"LEFT JOIN " . 'ybr_region' . " AS p ON o.province = p.region_id " .
	                	"LEFT JOIN " . 'ybr_region' . " AS t ON o.city = t.region_id " .
	                	"LEFT JOIN " . 'ybr_region' . " AS d ON o.district = d.region_id " .
	            		"WHERE o.order_id = '$order[order_id]'";
	    $region		=	$CommonModel->getOne($sql);
	    $order['region']	=	$region;
	    /* 格式化金额 */
	    if ($order['order_amount'] < 0){
	        $order['money_refund']          = abs($order['order_amount']); // abc 返回的是一个数的绝对值
	        $order['formated_money_refund'] = price_format(abs($order['order_amount']));
	    }	    
	    /* 其他处理 */
	    $lang_os	=	L('os'); // 订单状态
		$lang_ps	=	L('ps'); // 付款状态
		$lang_ss	=	L('ss'); // 发货状态	
	    $order['order_time']    = 	local_date("Y-m-d h:m:s", $order['add_time']);
	    $order['pay_time']      = 	$order['pay_time'] > 0 ? local_date("Y-m-d h:m:s", $order['pay_time']) : $lang_ps[PS_UNPAYED];
	    $order['shipping_time'] = 	$order['shipping_time'] > 0 ? local_date("Y-m-d h:m:s", $order['shipping_time']) : $lang_ss[SS_UNSHIPPED];
	    $order['status']        = 	$lang_os[$order['order_status']]. ',' . $lang_ps[$order['pay_status']] . ',' .  $lang_ss[$order['shipping_status']];
	    $order['invoice_no']    = 	$order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ?  $lang_ss[SS_UNSHIPPED] : $order['invoice_no'];

	    /* 此订单的发货备注(此订单的最后一条操作记录) */
	    $sql 					= 	"SELECT action_note FROM " . 'ybr_order_action'.
	           						" WHERE order_id = '$order[order_id]' AND shipping_status = 1 ORDER BY log_time DESC limit 1";
	    $order['invoice_note']	=	$CommonModel->getOne("SELECT action_note FROM ybr_order_action WHERE order_id = '1' AND shipping_status = 1 ORDER BY log_time DESC");
	    
	    /* 取得用户信息 */
	    if ($order['user_id'] > 0){
	        /* 用户等级 */
	        if ($user['user_rank'] > 0){
	            $where = " WHERE rank_id = '$user[user_rank]' ";
	        }
	        else{
	            $where = " WHERE min_points <= " . intval($user['rank_points']) . " ORDER BY min_points DESC ";
	        }
	        $sql = "SELECT rank_name FROM " . 'ybr_user_rank' . $where;
	        
	        //$user['rank_name'] = $db->getOne($sql);
	        $user['rank_name'] = $CommonModel->getOne($sql);
	
	        // 用户红包数量
	        $day    = 	getdate();
	        $today  = 	local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);
	        $sql 	= 	"SELECT COUNT(*) " .
	                	"FROM " . 'ybr_bonus_type' . " AS bt, " . 'user_bonus' . " AS ub " .
	                	"WHERE bt.type_id = ub.bonus_type_id " .
	                	"AND ub.user_id = '$order[user_id]' " .
	                	"AND ub.order_id = 0 " .
	                	"AND bt.use_start_date <= '$today' " .
	                	"AND bt.use_end_date >= '$today'";
	        
	        $user['bonus_count'] = $CommonModel->getOne($sql);
	        // 用户信息
	        $this->assign('user', $user);	
	        // 地址信息
	        $sql 			= 	"SELECT * FROM " . 'ybr_user_address' . " WHERE user_id = '$order[user_id]'";
	        $addressInfo	=	M()->query($sql);
	        $this->assign("addressInfo",$addressInfo);
	    }
	    
	    /* 取得订单商品总重量 */
	    $weight_price 			= 	$OrderModel->order_weight_price($order['order_id']);
	    $order['total_weight'] 	= 	$weight_price['formated_weight'];
	    
	    /* 参数赋值：订单 */
	    $this->assign('order', $order);
	    
	    /* 取得订单商品及货品 */
	    $goods_list = 	array();
	    $goods_attr = 	array();
	    $sql 		= 	"SELECT o.*, IF(o.product_id > 0, p.product_number, g.goods_number) AS storage, o.goods_attr, g.suppliers_id, IFNULL(b.brand_name, '') AS brand_name, p.product_sn
	            		FROM " . 'ybr_order_goods' . " AS o
	                	LEFT JOIN " . 'ybr_products' . " AS p
	                    ON p.product_id = o.product_id
	                	LEFT JOIN " . 'ybr_goods' . " AS g
	                    ON o.goods_id = g.goods_id
	                	LEFT JOIN " . 'ybr_brand' . " AS b
	                    ON g.brand_id = b.brand_id
	            		WHERE o.order_id = '$order[order_id]'";
	    
	    $res 		= 	M()->query($sql);
	    foreach($res as $row){
	    	/* 虚拟商品支持 */
	        if ($row['is_real'] == 0){
	            /* 取得语言项 
	            $filename = ROOT_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $GLOBALS['_CFG']['lang'] . '.php';
	            if (file_exists($filename))
	            {
	                include_once($filename);
	                if (!empty($_LANG[$row['extension_code'].'_link']))
	                {
	                    $row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
	                }
	            }
	            */
	        }	
	        $row['formated_subtotal']       = 	price_format($row['goods_price'] * $row['goods_number']);
	        $row['formated_goods_price']    = 	price_format($row['goods_price']);
	
	        $goods_attr[] 					= 	explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组
	
	        if ($row['extension_code'] == 'package_buy'){
	            $row['storage'] = '';
	            $row['brand_name'] = '';
	            $row['package_goods_list'] 	= 	$OrderModel->get_package_goods($row['goods_id']);
	        }	
	        $goods_list[] = $row;
	    }
	    
	    $attr 					= 	array();
	    $arr  					= 	array();
	    foreach ($goods_attr AS $index => $array_val){
	        foreach ($array_val AS $value){
	            $arr 			= 	explode(':', $value);//以 : 号将属性拆开
	            $attr[$index][] =  	@array('name' => $arr[0], 'value' => $arr[1]);
	        }
	    }	    
	    $this->assign('goods_attr', $attr);
	    $this->assign('goods_list', $goods_list);
			    
	    /* 取得能执行的操作列表 */
	    $OperatorMOdel		=	new OperatorModel();
	    $operable_list 		= 	$OperatorMOdel->get_perable_list($order);	    
	    $this->assign('operable_list', $operable_list);
		
	    //t($operable_list);
	    
	    /* 取得订单操作记录 */
	    $act_list 			= 	array();
	    $sql 				= 	"SELECT * FROM " . 'ybr_order_action' . " WHERE order_id = '$order[order_id]' ORDER BY log_time DESC,action_id DESC";
	    $res 				= 	M()->query($sql);
	    
	    foreach($res as $row){
	    	$row['order_status']    = 	$lang_os[$row['order_status']];
	        $row['pay_status']      = 	$lang_ps[$row['pay_status']];
	        $row['shipping_status'] = 	$lang_ss[$row['shipping_status']];
	        $row['action_time']     = 	local_date("Y-m-d H:m:s", $row['log_time']);
	        $act_list[] 			= 	$row;
	    }	    
	    $this->assign('action_list', $act_list);
	    
	    /* 取得是否存在实体商品 */
	    $exist_real_goods			=	$OrderModel->exist_real_goods($order['order_id']);
	    $this->assign('exist_real_goods', $exist_real_goods);
	    
	    /* 是否打印订单，分别赋值 */
	    if (isset($_GET['print'])){
	        $this->assign('shop_name',    		 $GLOBALS['_CFG']['shop_name']);
	        $this->assign('shop_url',     				         __ROOT__);
	        $this->assign('shop_address', 	  $GLOBALS['_CFG']['shop_address']);
	        $this->assign('service_phone',	 $GLOBALS['_CFG']['service_phone']);
	        $this->assign('print_time',   local_date($GLOBALS['_CFG']['time_format']));
	        $this->assign('action_user',  $_SESSION['admin_name']);
	        
	        $this->display('order_print');
	    }/* 打印快递单 */	    
	    elseif (isset($_GET['shipping_print'])){
	        //$this->assign('print_time',   local_date($GLOBALS['_CFG']['time_format']));
	        //发货地址所在地
	        $region_array 		= 	array();
	        $region_id 			= 	!empty($GLOBALS['_CFG']['shop_country']) ? $GLOBALS['_CFG']['shop_country'] . ',' : '';
	        $region_id 			.= 	!empty($GLOBALS['_CFG']['shop_province']) ? $GLOBALS['_CFG']['shop_province'] . ',' : '';
	        $region_id 			.= 	!empty($GLOBALS['_CFG']['shop_city']) ? $GLOBALS['_CFG']['shop_city'] . ',' : '';
	        $region_id 			= 	substr($region_id, 0, -1);
	        $region 			= 	M()->query("SELECT region_id, region_name FROM " . "ybr_region" . " WHERE region_id IN ($region_id)");
	        if (!empty($region)){
	            foreach($region as $region_data){
	                $region_array[$region_data['region_id']] = $region_data['region_name'];
	            }
	        }
	        $this->assign('shop_name',    			$GLOBALS['_CFG']['shop_name']);
	        $this->assign('order_id',   						   $order_id);
	        $this->assign('province',  $region_array[$GLOBALS['_CFG']['shop_province']]);
	        $this->assign('city', 		   $region_array[$GLOBALS['_CFG']['shop_city']]);
	        $this->assign('shop_address',			   $GLOBALS['_CFG']['shop_address']);
	        $this->assign('service_phone',			  $GLOBALS['_CFG']['service_phone']);
	        $shipping =	$CommonModel->getRow("SELECT * FROM " . "ybr_shipping" . " WHERE shipping_id = " . $order['shipping_id']);
	
	        //打印单模式
	        if ($shipping['print_model'] == 2){
	            /* 可视化 */
	            /* 快递单 */
	            $shipping['print_bg'] = empty($shipping['print_bg']) ? '' : get_site_root_url() . $shipping['print_bg'];
	
	            /* 取快递单背景宽高 */
	            if (!empty($shipping['print_bg'])){
	                $_size = @getimagesize($shipping['print_bg']);
	
	                if ($_size != false){
	                    $shipping['print_bg_size'] = array('width' => $_size[0], 'height' => $_size[1]);
	                }
	            }
	
	            if (empty($shipping['print_bg_size'])){
	                $shipping['print_bg_size'] = array('width' => '1024', 'height' => '600');
	            }
	
	            /* 标签信息 */
	            $lable_box = array();
	            $lable_box['t_shop_country'] = $region_array[$GLOBALS['_CFG']['shop_country']]; //网店-国家
	            $lable_box['t_shop_city'] = $region_array[$GLOBALS['_CFG']['shop_city']]; //网店-城市
	            $lable_box['t_shop_province'] = $region_array[$GLOBALS['_CFG']['shop_province']]; //网店-省份
	            $lable_box['t_shop_name'] = $GLOBALS['_CFG']['shop_name']; //网店-名称
	            $lable_box['t_shop_district'] = ''; //网店-区/县
	            $lable_box['t_shop_tel'] = $GLOBALS['_CFG']['service_phone']; //网店-联系电话
	            $lable_box['t_shop_address'] = $GLOBALS['_CFG']['shop_address']; //网店-地址
	            $lable_box['t_customer_country'] = $region_array[$order['country']]; //收件人-国家
	            $lable_box['t_customer_province'] = $region_array[$order['province']]; //收件人-省份
	            $lable_box['t_customer_city'] = $region_array[$order['city']]; //收件人-城市
	            $lable_box['t_customer_district'] = $region_array[$order['district']]; //收件人-区/县
	            $lable_box['t_customer_tel'] = $order['tel']; //收件人-电话
	            $lable_box['t_customer_mobel'] = $order['mobile']; //收件人-手机
	            $lable_box['t_customer_post'] = $order['zipcode']; //收件人-邮编
	            $lable_box['t_customer_address'] = $order['address']; //收件人-详细地址
	            $lable_box['t_customer_name'] = $order['consignee']; //收件人-姓名
	
	            $gmtime_utc_temp = gmtime(); //获取 UTC 时间戳
	            $lable_box['t_year'] = date('Y', $gmtime_utc_temp); //年-当日日期
	            $lable_box['t_months'] = date('m', $gmtime_utc_temp); //月-当日日期
	            $lable_box['t_day'] = date('d', $gmtime_utc_temp); //日-当日日期
	
	            $lable_box['t_order_no'] = $order['order_sn']; //订单号-订单
	            $lable_box['t_order_postscript'] = $order['postscript']; //备注-订单
	            $lable_box['t_order_best_time'] = $order['best_time']; //送货时间-订单
	            $lable_box['t_pigeon'] = '√'; //√-对号
	            $lable_box['t_custom_content'] = ''; //自定义内容
	
	            //标签替换
	            $temp_config_lable = explode('||,||', $shipping['config_lable']);
	            if (!is_array($temp_config_lable)){
	                $temp_config_lable[] = $shipping['config_lable'];
	            }
	            foreach ($temp_config_lable as $temp_key => $temp_lable){
	                $temp_info = explode(',', $temp_lable);
	                if (is_array($temp_info)){
	                    $temp_info[1] = $lable_box[$temp_info[0]];
	                }
	                $temp_config_lable[$temp_key] = implode(',', $temp_info);
	            }
	            $shipping['config_lable'] = implode('||,||',  $temp_config_lable);
	
	            $this->assign('shipping', $shipping);	
	            $this->display('print.htm');
	        }
	        elseif (!empty($shipping['shipping_print'])){
	            /* 代码 */
	            //echo $this->fetch("str:" . $shipping['shipping_print']);
	        }
	        else{
	            $shipping_code = $CommonModel->getOne("SELECT shipping_code FROM " . 'ybr_shipping' . " WHERE shipping_id=" . $order['shipping_id']);
	            if ($shipping_code){
	                include_once(ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php');
	            }
	
	            if (!empty($_LANG['shipping_print'])){
	                echo $this->fetch("str:$_LANG[shipping_print]");
	            }
	            else{
	                echo $_LANG['no_print_shipping'];
	            }
	        }
	    }  
		$this->display();
	}
	
	/**
	 * 订单列表
	 * @param	$_POST
	 * 
	 */
	public function order_list(){
		
		// 订单状态列表
		$lang_order_list		=	L('order_list');
		$this->assign("orderStatusList",$lang_order_list['order_status_list']);
		$this->assign("os_unconfirmed",		OS_UNCONFIRMED);
		$this->assign("cs_await_pay",		  CS_AWAIT_PAY);
		$this->assign("cs_await_ship",		 CS_AWAIT_SHIP);	
		// 订单列表
		$OrderModel			=	new OrderModel();	
		
		$sql_order_list		=	$OrderModel->get_sql_order_list();
		
		
		$param = array(
				'result'=>$sql_order_list,					//分页用的数组或sql
				'listvar'=>'orderList',		//分页循环变量
				'listRows'=>10,					//每页记录数
				'parameter'=>'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'=>'content',	    	//ajax更新内容的容器id，不带#
				'pagesId'=>'page',				//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'=>'Library:goods_list',//ajax更新模板
		);
		$this->order_page($param);
		$this->display();
	}
	
	/**
	 +----------------------------------------------------------
	 * 分页函数 支持sql和数据集分页 sql请用 buildSelectSql()函数生成
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param array  $result 排好序的数据集或者查询的sql语句
	 * @param int    $totalRows  每页显示记录数 默认21
	 * @param string $listvar    赋给模板遍历的变量名 默认list
	 * @param string $parameter  分页跳转的参数
	 * @param string $target  分页后点链接显示的内容id名
	 * @param string $pagesId  分页后点链接元素外层id名
	 * @param string $template ajaxlist的模板名
	 * @param string $url ajax分页自定义的url
	 +----------------------------------------------------------
	 */
	public function order_page($param) {
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置
		
		$lang_os	=	L('os'); // 订单状态
		$lang_ps	=	L('ps'); // 付款状态
		$lang_ss	=	L('ss'); // 买家状态		
	 	// 格式话数据
	    foreach ($voList AS $key => $value){
	        $voList[$key]['formated_order_amount'] 	= 	$value['order_amount'];
	        $voList[$key]['formated_money_paid'] 	=	$value['money_paid'];
	        $voList[$key]['formated_total_fee'] 	= 	$value['total_fee'];
	        $voList[$key]['short_order_time'] 		= 	local_date('m-d H:i', $value['add_time']);
	        // 
	        $voList[$key]['order_status_text']		=	$lang_os[$value['order_status']];
	        $voList[$key]['pay_status_text']		=	$lang_ps[$value['pay_status']];
	        $voList[$key]['shipping_status_text']	=	$lang_ss[$value['shipping_status']];
	        
	        if($value['order_status'] == OS_INVALID || $value['order_status'] == OS_CANCELED){
	            /* 如果该订单为无效或取消则显示删除链接 */
	            $voList[$key]['can_remove'] = 1;
	        }
	        else{
	            $$voList[$key]['can_remove'] = 0;
	        }
	    }
	    
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
	
	/**
	 * 订单查询
	 * 
	 */
	public function order_query(){
		
		$this->display();
	}
	
	/**
	 * 订单合并
	 * 
	 */
	public function order_merge(){	
				
	    /* 取得满足条件的订单 */
	    $sql 			= 	"SELECT o.order_sn, u.user_name " .
	            			"FROM " . 'ybr_order_info' . " AS o " .
	                		"LEFT JOIN " . 'ybr_users' . " AS u ON o.user_id = u.user_id " .
	            			"WHERE o.user_id > 0 " .
	            			"AND o.extension_code = '' " . order_query_sql('unprocessed');
	    $order_list		=	M()->query($sql);
	    $this->assign('order_list', $order_list);	
		$this->display();
	}
	
	/**
	 * ajax 处理合并订单 
	 * 
	 */
	public function ajax_merge_order(){
		/* 获取参数 */	
	    $from_order_sn 	= 	empty($_POST['from_order_sn']) ? '' : substr($_POST['from_order_sn'], 1);
	    $to_order_sn 	= 	empty($_POST['to_order_sn']) ? '' : substr($_POST['to_order_sn'], 1);
	
	    $m_result 		= 	merge_order($from_order_sn, $to_order_sn);
	    $result 		= 	array('error'=>0,  'content'=>'');
	    if ($m_result === true){
	        $result['message'] =  L('act_ok');
	    }
	    else{
	        $result['error'] 	= 	1;
	        $result['message'] 	= 	$m_result;
	    }
	    $this->ajaxReturn($result);
	}
	
	/**
	 * 订单打印
	 * 
	 */
	public function order_template(){
		
		$this->display();
	}
	
	/**
	 * 添加订单
	 * 
	 */
	public function add_order(){
		
		$this->display();
	}
	
	
	/**
	 * 退货单列表
	 * 
	 */
	public function back_list(){	
	    /* 模板赋值 */
	    $this->assign('ur_here', $_LANG['10_back_order']);
	
	    $this->assign('os_unconfirmed',   OS_UNCONFIRMED);
	    $this->assign('cs_await_pay',     CS_AWAIT_PAY);
	    $this->assign('cs_await_ship',    CS_AWAIT_SHIP);
	    $this->assign('filter',       $result['filter']);
	    $this->assign('sort_update_time', '<img src="' . __PUBLIC__ . '/Image/Admin/sort_desc.gif">');
		
	    $OrderModel			=	new OrderModel();
		$sql_order_list		=	$OrderModel->get_sql_back_list();
		
		$param = array(
				'result'=>$sql_order_list,		//分页用的数组或sql
				'listvar'=>'backList',			//分页循环变量
				'listRows'=>10,					//每页记录数
				'parameter'=>'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'=>'content',	    	//ajax更新内容的容器id，不带#
				'pagesId'=>'page',				//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'=>'Order:back_list',	//ajax更新模板
		);
	    
	    $this->back_list_page($param);
		$this->display();
	}
	
	/**
	 * 退货单分页功能函数
	 * Enter description here ...
	 */
	public function back_list_page(){
		extract($param);
		//总记录数
		$flag 			= 	is_string($result);
		
		$listvar 		= 	$listvar ? $listvar : 'list';
		$listRows 		= 	$listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows 	= 	($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p 			= 	new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p 			= 	new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result 	.= 	" LIMIT {$p->firstRow},{$p->listRows}";
			$row 		= 	M()->query($result);
		} else {
			$row 		= 	array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages 			= 	C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置
		
		$lang_delivery_status	=	L('delivery_status'); // 发货状态		
	 	// 格式话数据
	    foreach ($row AS $key => $value){
	        $row[$key]['return_time'] 		= 	local_date($GLOBALS['_CFG']['time_format'], $value['return_time']);
	        $row[$key]['add_time'] 			= 	local_date($GLOBALS['_CFG']['time_format'], $value['add_time']);
	        $row[$key]['update_time'] 		= 	local_date($GLOBALS['_CFG']['time_format'], $value['update_time']);
	        if ($value['status'] == 1){
	            $row[$key]['status_name'] 	= 	$lang_delivery_status[1];
	        }
	        else{
	        	$row[$key]['status_name'] 	= 	$lang_delivery_status[0];
	        }
	    }
	    
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $row);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
	
	/**
	 * 操作
	 * 
	 */
	public function operate(){
		
		$OrderModel			=	new OrderModel();
		$CommonModel		=	new CommonModel();
		$UserModel			=	new UserModel();
		$SupplierModel		=	new SupplierModel();
		$OperatorMOdel		=	new OperatorModel();
		
		$order_id 			= 	'';	
	    /* 取得订单id（可能是多个，多个sn）和操作备注（可能没有） */
	    if(isset($_REQUEST['order_id'])){
	        $order_id= $_REQUEST['order_id'];
	    }
	    $batch          = isset($_REQUEST['batch']); // 是否批处理
	    $action_note    = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
	
	    /* 确认 */
	    if (isset($_POST['confirm'])){
	        $require_note   = false;
	        $action         = '确认';
	        $operation      = 'confirm';
	    }
	    /* 付款 */
	    elseif (isset($_POST['pay'])){	        
	        //admin_priv('order_ps_edit');/* 检查权限 */
	        $require_note   = $GLOBALS['_CFG']['order_pay_note'] == 1;
	        $action         = '付款';
	        $operation      = 'pay';
	    }
	    /* 未付款 */
	    elseif (isset($_POST['unpay'])){	       
	        //admin_priv('order_ps_edit'); /* 检查权限 */	
	        $require_note   = 	$GLOBALS['_CFG']['order_unpay_note'] == 1;
	        $order          = 	$OrderModel->get_order_info($order_id);
	        
	        if ($order['money_paid'] > 0){
	            $show_refund = true;
	        }
	        $anonymous      = $order['user_id'] == 0;
	        $action         = '设为未付款';
	        $operation      = 'unpay';
	    }
	    /* 配货 */
	    elseif (isset($_POST['prepare'])){
	        $require_note   = false;
	        $action         = '配货';
	        $operation      = 'prepare';
	    }
	    /* 分单 */
	    elseif (isset($_POST['ship'])){
	        	
	        $order_id 		= 	intval(trim($order_id));
	        $action_note 	= 	trim($action_note);
	
	        /* 查询：根据订单id查询订单信息 */
	        if (!empty($order_id)){
	            $order = $OrderModel->get_order_info($order_id);
	        }
	        else{
	            die('order does not exist');
	        }
	        	        	
	        /* 查询：如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
	        $sql = "SELECT agency_id FROM " . 'ybr_admin_user' . " WHERE user_id = '$_SESSION[admin_id]'";
	        $agency_id = $CommonModel->getOne($sql);
	        if($agency_id > 0){
	            if ($order['agency_id'] != $agency_id){
	                //$this->error("对不起,您没有执行此项操作的权限!");
	            }
	        }
	
	        /* 查询：取得用户名 */
	        if ($order['user_id'] > 0){
	            $user 					= 	user_info($order['user_id']);
	            if (!empty($user)){
	                $order['user_name'] = 	$user['user_name'];
	            }
	        }
	
	        /* 查询：取得区域名 */
	        $sql 	= 	"SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
	                    "'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
	                	"FROM " . 'ybr_order_info' . " AS o " .
	                    "LEFT JOIN " . 'ybr_region' . " AS c ON o.country = c.region_id " .
	                    "LEFT JOIN " . 'ybr_region' . " AS p ON o.province = p.region_id " .
	                    "LEFT JOIN " . 'ybr_region' . " AS t ON o.city = t.region_id " .
	                    "LEFT JOIN " . 'ybr_region' . " AS d ON o.district = d.region_id " .
	                	"WHERE o.order_id = '$order[order_id]'";
	        $order['region'] 	= 	$CommonModel->getOne($sql);
	
	        /* 查询：其他处理 */
	        $lang_os	=	L('os'); // 订单状态
			$lang_ps	=	L('ps'); // 付款状态
			$lang_ss	=	L('ss'); // 买家状态	
	        $order['order_time']    = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);
	        $order['invoice_no']    = $order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ? $lang_ss[SS_UNSHIPPED] : $order['invoice_no'];
			/* 查询：供应商 */
	        $suppliers_list = 	$SupplierModel->get_suppliers_list();
	        $suppliers_list_count 	= 	count($suppliers_list);
	        $suppliers_name_list	=	suppliers_list_name();
	        $this->assign('suppliers_name', $suppliers_name_list); // 取供货商名
	        $this->assign('suppliers_list', ($suppliers_list_count == 0 ? 0 : $suppliers_list)); // 取供货商列表
	        /* 查询：是否保价 */
	        $order['insure_yn'] = empty($order['insure_fee']) ? 0 : 1;
	
	        /* 查询：是否存在实体商品 */
	        $exist_real_goods = $OrderModel->exist_real_goods($order_id);
	
	        /* 查询：取得订单商品 */
	        $_goods 	= $OrderModel->get_order_goods(array('order_id' => $order['order_id'], 'order_sn' =>$order['order_sn']));
	        $attr 		= $_goods['attr'];
	        $goods_list = $_goods['goods_list'];
	        unset($_goods);	
	        /* 查询：商品已发货数量 此单可发货数量 */
	        if ($goods_list){
	            foreach ($goods_list as $key=>$goods_value){
	                if (!$goods_value['goods_id']){
	                    continue;
	                }
	                /*对应供应商*/
	                 $goods_list[$key]['suppliers_name']	=	$suppliers_name_list[$goods_list[$key]['suppliers_id']];
	                /* 超级礼包 */
	                if (($goods_value['extension_code'] == 'package_buy') && (count($goods_value['package_goods_list']) > 0)){
	                    $goods_list[$key]['package_goods_list'] = package_goods($goods_value['package_goods_list'], $goods_value['goods_number'], $goods_value['order_id'], $goods_value['extension_code'], $goods_value['goods_id']);
	
	                    foreach ($goods_list[$key]['package_goods_list'] as $pg_key => $pg_value){
	                        $goods_list[$key]['package_goods_list'][$pg_key]['readonly'] = '';
	                        /* 使用库存 是否缺货 */
	                        if ($pg_value['storage'] <= 0 && $this->CFG['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_SHIP){
	                            $goods_list[$key]['package_goods_list'][$pg_key]['send'] = L('act_good_vacancy');
	                            $goods_list[$key]['package_goods_list'][$pg_key]['readonly'] = 'readonly="readonly"';
	                        }
	                        /* 将已经全部发货的商品设置为只读 */
	                        elseif ($pg_value['send'] <= 0){
	                            $goods_list[$key]['package_goods_list'][$pg_key]['send'] = L('act_good_delivery');
	                            $goods_list[$key]['package_goods_list'][$pg_key]['readonly'] = 'readonly="readonly"';
	                        }
	                    }
	                }
	                else{
	                    $goods_list[$key]['sended'] = $goods_value['send_number'];
	                    $goods_list[$key]['send'] = $goods_value['goods_number'] - $goods_value['send_number'];
	
	                    $goods_list[$key]['readonly'] = '';
	                    /* 是否缺货 */
	                    if ($goods_value['storage'] <= 0 && $GLOBALS['_CFG']['use_storage'] == '1'  && $GLOBALS['_CFG']['stock_dec_time'] == SDT_SHIP){
	                        $goods_list[$key]['send'] = L('act_good_vacancy');
	                        $goods_list[$key]['readonly'] = 'readonly="readonly"';
	                    }
	                    elseif ($goods_list[$key]['send'] <= 0){
	                        $goods_list[$key]['send'] = L('act_good_delivery');
	                        $goods_list[$key]['readonly'] = 'readonly="readonly"';
	                    }
	                }
	            }
	        }
	        
	        /* 模板赋值 */
	        $this->assign('order', $order);
	        $this->assign('exist_real_goods', $exist_real_goods);
	        $this->assign('goods_attr', $attr);
	        $this->assign('goods_list', $goods_list);
	        $this->assign('order_id', $order_id); // 订单id
	        $this->assign('operation', 'split'); // 订单id
	        $this->assign('action_note', $action_note); // 发货操作信息
	        /* 显示模板 */
	        $this->display('order_delivery_info');
	        exit();
		}
	    /* 未发货 */
	    elseif (isset($_POST['unship'])){	        
	        //admin_priv('order_ss_edit');/* 检查权限 */
	        $require_note   = $GLOBALS['_CFG']['order_unship_note'] == 1;
	        $action         = L('op_unship');
	        $operation      = 'unship';
	    }
	    /* 收货确认 */
	    elseif (isset($_POST['receive'])){
	        $require_note   = $GLOBALS['_CFG']['order_receive_note'] == 1;
	        $action         = L('op_receive');
	        $operation      = 'receive';
	    }
	    /* 取消 */
	    elseif (isset($_POST['cancel'])){
	        $require_note   = $GLOBALS['_CFG']['order_cancel_note'] == 1;
	        $action         = L('op_cancel');
	        $operation      = 'cancel';
	        $show_cancel_note   = true;
	        $order          = $OrderModel->get_order_goods($order);
	        if ($order['money_paid'] > 0){
	            $show_refund = true;
	        }
	        $anonymous      = $order['user_id'] == 0;
	    }
	    /* 无效 */
	    elseif (isset($_POST['invalid'])){
	        $require_note   = $GLOBALS['_CFG']['order_invalid_note'] == 1;
	        $action         = L('op_invalid');
	        $operation      = 'invalid';
	    }
	    /* 售后 */
	    elseif (isset($_POST['after_service'])){
	        $require_note   = true;
	        $action         = L('op_after_service');
	        $operation      = 'after_service';
	    }
	    /* 退货 */
	    elseif (isset($_POST['return'])){
	        $require_note   = $GLOBALS['_CFG']['order_return_note'] == 1;
	        $order          = $OrderModel->get_order_info($order_id);
	        if ($order['money_paid'] > 0){
	            $show_refund = true;
	        }
	        $anonymous      = $order['user_id'] == 0;
	        $action         = $_LANG['op_return'];
	        $operation      = 'return';	
	    }
	    /* 指派 */
	    elseif (isset($_POST['assign'])){
	        /* 取得参数 */
	        $new_agency_id  = isset($_POST['agency_id']) ? intval($_POST['agency_id']) : 0;
	        if ($new_agency_id == 0){
	            //sys_msg($_LANG['js_languages']['pls_select_agency']);
	            $this->error("请选择办事处！");
	        }
	
	        /* 查询订单信息 */
	        $order = $OrderModel->get_order_info($order_id);
	
	        /* 如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
	        $sql = "SELECT agency_id FROM " . 'ybr_admin_user' . " WHERE user_id = '$_SESSION[admin_id]'";
	        $admin_agency_id = $CommonModel->getOne($sql);
	        if ($admin_agency_id > 0){
	            if ($order['agency_id'] != $admin_agency_id){
	                //sys_msg($_LANG['priv_error']);
	                $this->error("对不起,您没有执行此项操作的权限!");
	            }
	        }
	
	        /* 修改订单相关所属的办事处 */
	        if ($new_agency_id != $order['agency_id']){
	            /*$query_array = array('order_info', // 更改订单表的供货商ID
	                                 'delivery_order', // 更改订单的发货单供货商ID
	                                 'back_order'// 更改订单的退货单供货商ID
	            );*/
	            $query_array = array('ybr_order_info', // 更改订单表的供货商ID
	                                 'ybr_delivery_order', // 更改订单的发货单供货商ID
	                                 'ybr_back_order'// 更改订单的退货单供货商ID
	            );	            
	            foreach ($query_array as $value){
	                $CommonModel->query("UPDATE " . $value . " SET agency_id = '$new_agency_id' " . " WHERE order_id = '$order_id'");
	            }
	        }	
	        /* 操作成功 */
	        $this->success("操作成功",U("order/order_list"));
	    }
	    /* 订单删除 */
	    elseif (isset($_POST['remove'])){
	        $require_note 	= 	false;
	        $operation 		= 	'remove';
	        if (!$batch){
	            /* 检查能否操作 */
	            $order = $OrderModel->get_order_info($order_id);
	            $operable_list = $OperatorMOdel->get_operable_list($order);
	            if (!isset($operable_list['remove'])){
	                die('Hacking attempt');
	            }
	
	            /* 删除订单 */
	            $CommonModel->query("DELETE FROM ".'ybr_order_info'. " WHERE order_id = '$order_id'");
	            $CommonModel->query("DELETE FROM ".'ybr_order_goods'. " WHERE order_id = '$order_id'");
	            $CommonModel->query("DELETE FROM ".'ybr_order_action'. " WHERE order_id = '$order_id'");
	            $action_array = array('delivery', 'back');
	            $OrderModel->del_delivery($order_id, $action_array);
				/* todo 记录日志 */   
	            admin_log($order['order_sn'], 'remove', 'order');         	
	        }	        
	    }
	    /* 发货单删除 */
	    elseif (isset($_REQUEST['remove_invoice'])){
	        // 删除发货单
	        $delivery_id	=	$_REQUEST['delivery_id'];
	        $delivery_id 	= 	is_array($delivery_id) ? $delivery_id : array($delivery_id);
	
	        foreach($delivery_id as $value_is){
	            $value_is = intval(trim($value_is));
	
	            // 查询：发货单信息
	            $delivery_order = delivery_order_info($value_is);
	
	            // 如果status不是退货
	            if ($delivery_order['status'] != 1){
	                /* 处理退货 */
	                delivery_return_goods($value_is, $delivery_order);
	            }
	
	            // 如果status是已发货并且发货单号不为空
	            if ($delivery_order['status'] == 0 && $delivery_order['invoice_no'] != ''){
	                /* 更新：删除订单中的发货单号 */
	                del_order_invoice_no($delivery_order['order_id'], $delivery_order['invoice_no']);
	            }
	
	            // 更新：删除发货单
	            $sql = "DELETE FROM ".'ybr_delivery_order'. " WHERE delivery_id = '$value_is'";
	            $CommonModel->query($sql);
	        }
	
	        /* 返回 */
	        $this->success("发货单删除成功！",U('order/delivery_list'));
	    }
	     /* 退货单删除 */
	    elseif (isset($_REQUEST['remove_back'])){
	        $back_id = $_REQUEST['back_id'];
	        /* 删除退货单 */
	        if(is_array($back_id)){
		        foreach ($back_id as $value_is){
	                $sql = "DELETE FROM ".'ybr_back_order'. " WHERE back_id = '$value_is'";
	                M()->query($sql);
	            }
	        }
	        else{
	            $sql = "DELETE FROM ".'ybr_back_order'. " WHERE back_id = '$back_id'";
	           	M()->query($sql);
	        }
	        /* 返回 */
	        $this->success("退货单删除成功！",U('order/back_list'));
	    }
	    /* 批量打印订单 */
	    elseif (isset($_POST['print'])){
	        if (empty($_POST['order_id'])){
	            $this->error("请选择您要操作的订单");
	        }
	
	        /* 赋值公用信息 */
	        $this->assign('shop_name',    $GLOBALS['_CFG']['shop_name']);
	        $this->assign('shop_url',     __ROOT__);
	        $this->assign('shop_address', $GLOBALS['_CFG']['shop_address']);
	        $this->assign('service_phone',$GLOBALS['_CFG']['service_phone']);
	        $this->assign('print_time',   local_date($GLOBALS['_CFG']['time_format']));
	        $this->assign('action_user',  $_SESSION['admin_name']);
	
	        $html = '';
	        $order_sn_list = explode(',', $_POST['order_id']);
	        foreach ($order_sn_list as $order_sn){
	            /* 取得订单信息 */
	            $order = order_info(0, $order_sn);
	            if (empty($order)){
	                continue;
	            }
	
	            /* 根据订单是否完成检查权限 */
	            if (order_finished($order)){
	                if (!admin_priv('order_view_finished', '', false)){
	                    continue;
	                }
	            }
	            else{
	                if (!admin_priv('order_view', '', false)){
	                    continue;
	                }
	            }
	
	            /* 如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
	            $sql = "SELECT agency_id FROM " . 'ybr_admin_user' . " WHERE user_id = '$_SESSION[admin_id]'";
	            $agency_id = $CommonModel->getOne($sql);
	            if ($agency_id > 0){
	                if ($order['agency_id'] != $agency_id){
	                    continue;
	                }
	            }
	
	            /* 取得用户名 */
	            if ($order['user_id'] > 0){
	                $user = user_info($order['user_id']);
	                if (!empty($user)){
	                    $order['user_name'] = $user['user_name'];
	                }
	            }
	
	            /* 取得区域名 */
	            $sql = 	"SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
	                    "'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
	                    "FROM " . 'ybr_order_info' . " AS o " .
	                    "LEFT JOIN " . 'ybr_region' . " AS c ON o.country = c.region_id " .
	                    "LEFT JOIN " . 'ybr_region' . " AS p ON o.province = p.region_id " .
	                    "LEFT JOIN " . 'ybr_region' . " AS t ON o.city = t.region_id " .
	                    "LEFT JOIN " . 'ybr_region' . " AS d ON o.district = d.region_id " .
	                    "WHERE o.order_id = '$order[order_id]'";
	            $order['region'] = $CommonModel->getOne($sql);
				
	            /* 其他处理 */
	            $lang_os	=	L('os'); // 订单状态
				$lang_ps	=	L('ps'); // 付款状态
				$lang_ss	=	L('ss'); // 发货状态	
	            $order['order_time']    = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);
	            $order['pay_time']      = $order['pay_time'] > 0 ? local_date($GLOBALS['_CFG']['time_format'], $order['pay_time']) : $lang_ps[PS_UNPAYED];
	            $order['shipping_time'] = $order['shipping_time'] > 0 ? local_date($GLOBALS['_CFG']['time_format'], $order['shipping_time']) : $lang_ps[SS_UNSHIPPED];
	            $order['status']        = $lang_os[ $order['order_status'] ] . ',' .  $lang_ps[ $order['pay_status'] ]  . ',' . $lang_ss[ $order['shipping_status'] ];
	            $order['invoice_no']    = $order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ? $_LANG['ss'][SS_UNSHIPPED] : $order['invoice_no'];
	
	            /* 此订单的发货备注(此订单的最后一条操作记录) */
	            $sql = "SELECT action_note FROM " . 'ybr_order_action' .
	                   " WHERE order_id = '$order[order_id]' AND shipping_status = 1 ORDER BY log_time DESC";
	            $order['invoice_note'] = $CommonModel->getOne($sql);
	
	            /* 参数赋值：订单 */
	            $this->assign('order', $order);
	
	            /* 取得订单商品 */
	            $goods_list = array();
	            $goods_attr = array();
	            $sql = "SELECT o.*, g.goods_number AS storage, o.goods_attr, IFNULL(b.brand_name, '') AS brand_name " .
	                    "FROM " . 'ybr_order_goods' . " AS o ".
	                    "LEFT JOIN " . 'ybr_goods' . " AS g ON o.goods_id = g.goods_id " .
	                    "LEFT JOIN " . 'ybr_brand' . " AS b ON g.brand_id = b.brand_id " .
	                    "WHERE o.order_id = '$order[order_id]' ";
	            $res = $CommonModel->query($sql);
	            foreach($res as $row){
	            	/* 虚拟商品支持 */
	                if ($row['is_real'] == 0){
	                    /* 取得语言项
	                    $filename = ROOT_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $GLOBALS['_CFG']['lang'] . '.php';
	                    if (file_exists($filename)){
	                        include_once($filename);
	                        if (!empty($_LANG[$row['extension_code'].'_link'])){
	                            $row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
	                        }
	                    } */	                    
	                }	
	                $row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
	                $row['formated_goods_price']    = price_format($row['goods_price']);
	
	                $goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组
	                $goods_list[] = $row;
	            }
	            
	            $attr = array();
	            $arr  = array();
	            foreach ($goods_attr AS $index => $array_val){
	                foreach ($array_val AS $value){
	                    $arr = explode(':', $value);//以 : 号将属性拆开
	                    $attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
	                }
	            }
	
	            $this->assign('goods_attr', $attr);
	            $this->assign('goods_list', $goods_list);
	
	           /* $this->template_dir = '../' . DATA_DIR;
	            $html .= $this->fetch('order_print.html') .
	                '<div style="PAGE-BREAK-AFTER:always"></div>';*/
	        }
	    }
	    /* 去发货 */
	    elseif (isset($_POST['to_delivery'])){
	    	$this->redirect("/order/delivery_list" . '?order_sn=' . $_REQUEST['order_sn']);
	    }
	    /* 直接处理还是跳到详细页面 */
	    if (($require_note && $action_note == '') || isset($show_invoice_no) || isset($show_refund)){	
	        /* 模板赋值 */
	        $this->assign('require_note', $require_note); // 是否要求填写备注
	        $this->assign('action_note', $action_note);   // 备注
	        $this->assign('show_cancel_note', isset($show_cancel_note)); // 是否显示取消原因
	        $this->assign('show_invoice_no', isset($show_invoice_no)); // 是否显示发货单号
	        $this->assign('show_refund', isset($show_refund)); // 是否显示退款
	        $this->assign('anonymous', isset($anonymous) ? $anonymous : true); // 是否匿名
	        $this->assign('order_id', $order_id); // 订单id
	        $this->assign('batch', $batch);   // 是否批处理
	        $this->assign('operation', $operation); // 操作
			
	        /* 显示模板 */
	        $this->assign('ur_here', L('order_operate') . $action);
	        $this->display('order_operate');
	    }
	    else{
	        /* 直接处理 */
	        if (!$batch){
	            /* 一个订单 */
	        	echo $operation;	        	
	            $this->redirect("/order/operate_post?order_id=" . $order_id . "&operation=" . $operation . "&action_note=" . urlencode($action_note) );
	        }
	        else{
	            /* 多个订单 */
	            $this->redirect("/order/batch_operate_post?order_id=" . $order_id . "&operation=" . $operation . "&action_note=" . urlencode($action_note) );
	        }
	    }		
	}
	
	
	public function operate_post(){
		
		$OrderModel			=	new OrderModel();
		$CommonModel		=	new CommonModel();
		$UserModel			=	new UserModel();
		$SupplierModel		=	new SupplierModel();
		$OperatorMOdel		=	new OperatorModel();
		
	    /* 取得参数 */
	    $order_id   = intval(trim($_REQUEST['order_id']));        // 订单id
	    $operation  = $_REQUEST['operation'];       // 订单操作
	
	    /* 查询订单信息 */
	    $order = $OrderModel->get_order_info($order_id);	    
	
	    /* 取得备注信息 */
	    $action_note = $_REQUEST['action_note'];
	
	    /* 初始化提示信息 */
	    $msg = '';
	
	    /* 确认 */
	    if ('confirm' == $operation){
	        /* 标记订单为已确认 */
	        update_order($order_id, array('order_status' => OS_CONFIRMED, 'confirm_time' => gmtime()));
	        update_order_amount($order_id);
			
	        /* 记录log */
        	order_action($order['order_sn'], OS_CONFIRMED, SS_UNSHIPPED, PS_UNPAYED, $action_note);
	        
	        /* 如果原来状态不是“未确认”，且使用库存，且下订单时减库存，则减少库存 */
	        if ($order['order_status'] != OS_UNCONFIRMED && $GLOBALS['_CFG']['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_PLACE){
	            change_order_goods_storage($order_id, true, SDT_PLACE); // 用户下单时减少库存
	        }	
	        $this->success("操作成功",U('order/order') . '?order_id=' . $order_id);
	    }
	    /* 付款 */
	    elseif ('pay' == $operation){
	
	        /* 标记订单为已确认、已付款，更新付款时间和已支付金额，如果是货到付款，同时修改订单为“收货确认” */
	        if ($order['order_status'] != OS_CONFIRMED){
	            $arr['order_status']    = OS_CONFIRMED;
	            $arr['confirm_time']    = gmtime();
	        }
	        $arr['pay_status']  = PS_PAYED;
	        $arr['pay_time']    = gmtime();
	        $arr['money_paid']  = $order['money_paid'] + $order['order_amount'];
	        $arr['order_amount']= 0;
	        $payment = payment_info($order['pay_id']);
	        if ($payment['is_cod']){
	            $arr['shipping_status'] = SS_RECEIVED;
	            $order['shipping_status'] = SS_RECEIVED;
	        }
	        update_order($order_id, $arr);
	        	           
			/* 记录log */
        	order_action($order['order_sn'], OS_CONFIRMED, $order['shipping_status'], PS_PAYED, $action_note);	        
			clear_cache(); // 清除缓存 
	    }
	    /* 设为未付款 */
	    elseif ('unpay' == $operation){
	        /* 标记订单为未付款，更新付款时间和已付款金额 */
	        $arr = array(
	            'pay_status'    => PS_UNPAYED,
	            'pay_time'      => 0,
	            'money_paid'    => 0,
	            'order_amount'  => $order['money_paid']
	        );
	        update_order($order_id, $arr);
	
	        /* todo 处理退款 */
	        $refund_type = @$_REQUEST['refund'];
	        $refund_note = @$_REQUEST['refund_note'];
	        $OrderModel->order_refund($order, $refund_type, $refund_note);
	        
	        /* 记录log */
        	order_action($order['order_sn'], OS_CONFIRMED, SS_UNSHIPPED, PS_UNPAYED, $action_note);
	       	clear_cache(); // 清除缓存 
	    }
	    /* 配货 */
	    elseif ('prepare' == $operation){
	        /* 标记订单为已确认，配货中 */
	        if ($order['order_status'] != OS_CONFIRMED){
	            $arr['order_status']    = OS_CONFIRMED;
	            $arr['confirm_time']    = gmtime();
	        }
	        $arr['shipping_status']     = SS_PREPARING;
	        update_order($order_id, $arr);
	        
	         /* 记录log */
        	order_action($order['order_sn'], OS_CONFIRMED, SS_PREPARING, $order['pay_status'], $action_note);
	        clear_cache();
	    }
	    /* 分单确认 */
	    elseif ('split' == $operation){
	    	//==============================================================================================================================	
	        /* 定义当前时间 */
	        define('GMTIME_UTC', gmtime()); // 获取 UTC 时间戳
			
	        /* 获取表单提交数据 */
	        $suppliers_id 			= 	isset($_REQUEST['suppliers_id']) ? intval(trim($_REQUEST['suppliers_id'])) : '0';
	        array_walk($_REQUEST['delivery'], 'trim_array_walk');
	        $delivery 				= 	$_REQUEST['delivery'];
	        array_walk($_REQUEST['send_number'], 'trim_array_walk');
	        array_walk($_REQUEST['send_number'], 'intval_array_walk');
	        $send_number 			= 	$_REQUEST['send_number'];
	        $action_note 			= 	isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
	        $delivery['user_id']  	= 	intval($delivery['user_id']);
	        $delivery['country']  	= 	intval($delivery['country']);
	        $delivery['province'] 	= 	intval($delivery['province']);
	        $delivery['city']     	= 	intval($delivery['city']);
	        $delivery['district'] 	= 	intval($delivery['district']);
	        $delivery['agency_id']    = 	intval($delivery['agency_id']);
	        $delivery['insure_fee']   = 	floatval($delivery['insure_fee']);
	        $delivery['shipping_fee'] = 	floatval($delivery['shipping_fee']);
			
	        /* 订单是否已全部分单检查 */
	        if ($order['order_status'] == OS_SPLITED){
	            /* 操作失败 
	            $links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
	            sys_msg(sprintf($_LANG['order_splited_sms'], $order['order_sn'],
	                    $_LANG['os'][OS_SPLITED], $_LANG['ss'][SS_SHIPPED_ING], $GLOBALS['_CFG']['shop_name']), 1, $links);*/
	            $this->error("操作失败",U('order/order') . '?order_id=' . $order_id);
	        }
	
	        /* 取得订单商品 */
	        $_goods 	= $OrderModel->get_order_goods(array('order_id' => $order_id, 'order_sn' => $delivery['order_sn']));
	        $goods_list = $_goods['goods_list'];
	        
	        /* 检查此单发货数量填写是否正确 合并计算相同商品和货品 */
	        if (!empty($send_number) && !empty($goods_list)){
	            $goods_no_package = array();
	            foreach ($goods_list as $key => $value){
	                /* 去除 此单发货数量 等于 0 的商品 */
	                if (!isset($value['package_goods_list']) || !is_array($value['package_goods_list'])){
	                    // 如果是货品则键值为商品ID与货品ID的组合
	                    $_key = empty($value['product_id']) ? $value['goods_id'] : ($value['goods_id'] . '_' . $value['product_id']);
	
	                    // 统计此单商品总发货数 合并计算相同ID商品或货品的发货数
	                    if (empty($goods_no_package[$_key])){
	                        $goods_no_package[$_key] = $send_number[$value['rec_id']];
	                    }
	                    else{
	                        $goods_no_package[$_key] += $send_number[$value['rec_id']];
	                    }
	
	                    //去除
	                    if ($send_number[$value['rec_id']] <= 0){
	                        unset($send_number[$value['rec_id']], $goods_list[$key]);
	                        continue;
	                    }
	                }
	                else{
	                    /* 组合超值礼包信息 */
	                    $goods_list[$key]['package_goods_list'] = package_goods($value['package_goods_list'], $value['goods_number'], $value['order_id'], $value['extension_code'], $value['goods_id']);
	
	                    /* 超值礼包 */
	                    foreach ($value['package_goods_list'] as $pg_key => $pg_value){
	                        // 如果是货品则键值为商品ID与货品ID的组合
	                        $_key = empty($pg_value['product_id']) ? $pg_value['goods_id'] : ($pg_value['goods_id'] . '_' . $pg_value['product_id']);
	
	                        //统计此单商品总发货数 合并计算相同ID产品的发货数
	                        if (empty($goods_no_package[$_key])){
	                            $goods_no_package[$_key] = $send_number[$value['rec_id']][$pg_value['g_p']];
	                        }
	                        //否则已经存在此键值
	                        else{
	                            $goods_no_package[$_key] += $send_number[$value['rec_id']][$pg_value['g_p']];
	                        }
	
	                        //去除
	                        if ($send_number[$value['rec_id']][$pg_value['g_p']] <= 0){
	                            unset($send_number[$value['rec_id']][$pg_value['g_p']], $goods_list[$key]['package_goods_list'][$pg_key]);
	                        }
	                    }
	
	                    if (count($goods_list[$key]['package_goods_list']) <= 0){
	                        unset($send_number[$value['rec_id']], $goods_list[$key]);
	                        continue;
	                    }
	                }
	
	                /* 发货数量与总量不符 */
	                if (!isset($value['package_goods_list']) || !is_array($value['package_goods_list'])){
	                    $sended = order_delivery_num($order_id, $value['goods_id'], $value['product_id']);
	                    if (($value['goods_number'] - $sended - $send_number[$value['rec_id']]) < 0){
	                        /* 操作失败 */
	                        //$links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
	                        //sys_msg($_LANG['act_ship_num'], 1, $links);
	                        $this->error("此单发货数量不能超出订单商品数量",U('order/order') . '?order_id=' . $order_id);
	                    }
	                }
	                else{
	                    /* 超值礼包 */
	                    foreach ($goods_list[$key]['package_goods_list'] as $pg_key => $pg_value){
	                        if (($pg_value['order_send_number'] - $pg_value['sended'] - $send_number[$value['rec_id']][$pg_value['g_p']]) < 0){
	                            /* 操作失败 
	                            $links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
	                            sys_msg($_LANG['act_ship_num'], 1, $links);*/
	                            $this->error("此单发货数量不能超出订单商品数量",U('order/order') . '?order_id=' . $order_id);
	                        }
	                    }
	                }
	            }
	        }
	        /* 对上一步处理结果进行判断 兼容 上一步判断为假情况的处理 */
	        if (empty($send_number) || empty($goods_list)){
	            /* 操作失败
	            $links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
	            sys_msg($_LANG['act_false'], 1, $links); */
	            $this->error("操作失败",U('order/order') . '?order_id=' . $order_id);
	        }
	
	        /* 检查此单发货商品库存缺货情况 */
	        /* $goods_list已经过处理 超值礼包中商品库存已取得 */
	        $virtual_goods = array();
	        $package_virtual_goods = array();
	        foreach ($goods_list as $key => $value){
	            // 商品（超值礼包）
	            if ($value['extension_code'] == 'package_buy'){
	                foreach ($value['package_goods_list'] as $pg_key => $pg_value){
	                    if ($pg_value['goods_number'] < $goods_no_package[$pg_value['g_p']] && (($GLOBALS['_CFG']['use_storage'] == '1'  && $GLOBALS['_CFG']['stock_dec_time'] == SDT_SHIP) || ($GLOBALS['_CFG']['use_storage'] == '0' && $pg_value['is_real'] == 0))){
	                        /* 操作失败 */
	                        //$links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
	                        //sys_msg(sprintf($_LANG['act_good_vacancy'], $pg_value['goods_name']), 1, $links);
	                        $this->error("商品已缺货",U('order/order') . '?order_id=' . $order_id);
	                    }
	
	                    /* 商品（超值礼包） 虚拟商品列表 package_virtual_goods*/
	                    if ($pg_value['is_real'] == 0){
	                        $package_virtual_goods[] = array(
	                                       'goods_id' => $pg_value['goods_id'],
	                                       'goods_name' => $pg_value['goods_name'],
	                                       'num' => $send_number[$value['rec_id']][$pg_value['g_p']]
	                                       );
	                    }
	                }
	            }
	            // 商品（虚货）
	            elseif ($value['extension_code'] == 'virtual_card' || $value['is_real'] == 0){
	                $sql = "SELECT COUNT(*) FROM " . 'ybr_virtual_card' . " WHERE goods_id = '" . $value['goods_id'] . "' AND is_saled = 0 ";
	                $num = $CommonModel->GetOne($sql);
	                if (($num < $goods_no_package[$value['goods_id']]) && !($GLOBALS['_CFG']['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_PLACE)){
	                    /* 操作失败 */
	                    //$links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
	                    //sys_msg(sprintf($GLOBALS['_LANG']['virtual_card_oos'] . '【' . $value['goods_name'] . '】'), 1, $links);
	                    $this->error(L('virtual_card_oos'),U('order/order') . '?order_id=' . $order_id);
	                }
	
	                /* 虚拟商品列表 virtual_card*/
	                if ($value['extension_code'] == 'virtual_card'){
	                    $virtual_goods[$value['extension_code']][] = array('goods_id' => $value['goods_id'], 'goods_name' => $value['goods_name'], 'num' => $send_number[$value['rec_id']]);
	                }
	            }
	            // 商品（实货）、（货品）
	            else{
	                //如果是货品则键值为商品ID与货品ID的组合
	                $_key = empty($value['product_id']) ? $value['goods_id'] : ($value['goods_id'] . '_' . $value['product_id']);
	
	                /* （实货） */
	                if (empty($value['product_id'])){
	                    $sql = "SELECT goods_number FROM " . 'ybr_goods' . " WHERE goods_id = '" . $value['goods_id'] . "' LIMIT 0,1";
	                }
	                /* （货品） */
	                else{
	                    $sql = "SELECT product_number
	                            FROM " . 'ybr_products' ."
	                            WHERE goods_id = '" . $value['goods_id'] . "'
	                            AND product_id =  '" . $value['product_id'] . "'
	                            LIMIT 0,1";
	                }
	                $num = $CommonModel->GetOne($sql);
	
	                if (($num < $goods_no_package[$_key]) && $GLOBALS['_CFG']['use_storage'] == '1'  && $GLOBALS['_CFG']['stock_dec_time'] == SDT_SHIP){
	                    /* 操作失败 
	                    $links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
	                    sys_msg(sprintf($_LANG['act_good_vacancy'], $value['goods_name']), 1, $links);*/
	                	$this->error(L('操作失败'),U('order/order') . '?order_id=' . $order_id);
	                }
	            }
	        }
	
	        /* 生成发货单 */
	        /* 获取发货单号和流水号 */
	        $delivery['delivery_sn'] 	= 	get_delivery_sn();
	        $delivery_sn 				= 	$delivery['delivery_sn'];
	        /* 获取当前操作员 */
	        $delivery['action_user'] 	= 	$_SESSION['admin_name'];
	        /* 获取发货单生成时间 */
	        $delivery['update_time'] 	= 	GMTIME_UTC;
	        $delivery_time 				= 	$delivery['update_time'];
	        $sql 						=	"select add_time from ". 'ybr_order_info' ." WHERE order_sn = '" . $delivery['order_sn'] . "'";
	        $delivery['add_time'] 		= 	 $CommonModel->GetOne($sql);
	        /* 获取发货单所属供应商 */
	        $delivery['suppliers_id'] 	= 	$suppliers_id;
	        /* 设置默认值 */
	        $delivery['status'] 		= 	2; // 正常
	        $delivery['order_id'] 		= 	$order_id;
	        /* 过滤字段项 */
	        $filter_fileds = array(
	                               'order_sn', 'add_time', 'user_id', 'how_oos', 'shipping_id', 'shipping_fee',
	                               'consignee', 'address', 'country', 'province', 'city', 'district', 'sign_building',
	                               'email', 'zipcode', 'tel', 'mobile', 'best_time', 'postscript', 'insure_fee',
	                               'agency_id', 'delivery_sn', 'action_user', 'update_time',
	                               'suppliers_id', 'status', 'order_id', 'shipping_name'
	                               );
	        $_delivery = array();
	        foreach ($filter_fileds as $value){
	            $_delivery[$value] = $delivery[$value];
	        }
	               
	        /* 发货单入库 */
	        $delivery_id = $CommonModel->autoExecute('delivery_order', $_delivery, 'INSERT', '');
	        
	        if($delivery_id){
	            $delivery_goods = array();
	
	            //发货单商品入库
	            if (!empty($goods_list)){
	                foreach ($goods_list as $value){
	                    // 商品（实货）（虚货）
	                    if (empty($value['extension_code']) || $value['extension_code'] == 'virtual_card'){
	                        $delivery_goods = array('delivery_id' => $delivery_id,
	                                                'goods_id' => $value['goods_id'],
	                                                'product_id' => $value['product_id'],
	                                                'product_sn' => $value['product_sn'],
	                                                'goods_id' => $value['goods_id'],
	                                                'goods_name' => addslashes($value['goods_name']),
	                                                'brand_name' => addslashes($value['brand_name']),
	                                                'goods_sn' => $value['goods_sn'],
	                                                'send_number' => $send_number[$value['rec_id']],
	                                                'parent_id' => 0,
	                                                'is_real' => $value['is_real'],
	                                                'goods_attr' => addslashes($value['goods_attr'])
	                                                );
	
	                        /* 如果是货品 */
	                        if (!empty($value['product_id'])){
	                            $delivery_goods['product_id'] = $value['product_id'];
	                        }
	
	                        $query = $CommonModel->autoExecute('delivery_goods', $delivery_goods, 'INSERT', '');
	                    }
	                    // 商品（超值礼包）
	                    elseif ($value['extension_code'] == 'package_buy'){
	                        foreach ($value['package_goods_list'] as $pg_key => $pg_value){
	                            $delivery_pg_goods = array('delivery_id' => $delivery_id,
	                                                    'goods_id' => $pg_value['goods_id'],
	                                                    'product_id' => $pg_value['product_id'],
	                                                    'product_sn' => $pg_value['product_sn'],
	                                                    'goods_name' => $pg_value['goods_name'],
	                                                    'brand_name' => '',
	                                                    'goods_sn' => $pg_value['goods_sn'],
	                                                    'send_number' => $send_number[$value['rec_id']][$pg_value['g_p']],
	                                                    'parent_id' => $value['goods_id'], // 礼包ID
	                                                    'extension_code' => $value['extension_code'], // 礼包
	                                                    'is_real' => $pg_value['is_real']
	                                                    );
	                            $query = $CommonModel->autoExecute('delivery_goods', $delivery_pg_goods, 'INSERT', '');
	                        }
	                    }
	                }
	            }
	        }
	        else{
	            /* 操作失败 */
	            //$links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
	            //sys_msg($_LANG['act_false'], 1, $links);
	            $this->error("操作失败,即将返回" . L('order_info'),U('order/order') . '?order_id=' . $order_id);
	        }
	        unset($filter_fileds, $delivery, $_delivery, $order_finish);
	
	        /* 定单信息更新处理 */
	        if (true){
	            /* 定单信息 */
	            $_sended = & $send_number;
	            foreach ($_goods['goods_list'] as $key => $value){
	                if ($value['extension_code'] != 'package_buy'){
	                    unset($_goods['goods_list'][$key]);
	                }
	            }
	            foreach ($goods_list as $key => $value){
	                if ($value['extension_code'] == 'package_buy'){
	                    unset($goods_list[$key]);
	                }
	            }
	            $_goods['goods_list'] = $goods_list + $_goods['goods_list'];
	            unset($goods_list);
	
	            /* 更新订单的虚拟卡 商品（虚货） */
	            $_virtual_goods = isset($virtual_goods['virtual_card']) ? $virtual_goods['virtual_card'] : '';
	            update_order_virtual_goods($order_id, $_sended, $_virtual_goods);
	
	            /* 更新订单的非虚拟商品信息 即：商品（实货）（货品）、商品（超值礼包）*/
	            update_order_goods($order_id, $_sended, $_goods['goods_list']);
	
	            /* 标记订单为已确认 “发货中” */
	            /* 更新发货时间 */
	            $order_finish = get_order_finish($order_id);
	            $shipping_status = SS_SHIPPED_ING;
	            if ($order['order_status'] != OS_CONFIRMED && $order['order_status'] != OS_SPLITED && $order['order_status'] != OS_SPLITING_PART){
	                $arr['order_status']    = OS_CONFIRMED;
	                $arr['confirm_time']    = GMTIME_UTC;
	            }
	            $arr['order_status'] = $order_finish ? OS_SPLITED : OS_SPLITING_PART; // 全部分单、部分分单
	            $arr['shipping_status']     = $shipping_status;
	            update_order($order_id, $arr);
	            
	            /* 记录log */
        		order_action($order['order_sn'], $arr['order_status'], $shipping_status, $order['pay_status'], $action_note);
	        }
	        //==============================================================================================================================
	    }
	    /* 设为未发货 */
	    elseif ('unship' == $operation){
	    	
	        /* 标记订单为“未发货”，更新发货时间, 订单状态为“确认” */
	        update_order($order_id, array('shipping_status' => SS_UNSHIPPED, 'shipping_time' => 0, 'invoice_no' => '', 'order_status' => OS_CONFIRMED));

	        /* 记录log */
        	order_action($order['order_sn'], $order['order_status'], SS_UNSHIPPED, $order['pay_status'], $action_note);
	        
	        /* 如果订单用户不为空，计算积分，并退回 */
	        if ($order['user_id'] > 0){
	            /* 取得用户信息 */
	            $user 				= 	user_info($order['user_id']);
	
	            /* 计算并退回积分 */
	            $integral 			= 	integral_to_give($order);
	            log_account_change($order['user_id'], 0, 0, (-1) * intval($integral['rank_points']), (-1) * intval($integral['custom_points']), sprintf($_LANG['return_order_gift_integral'], $order['order_sn']));
	
	            /* todo 计算并退回红包 */
	            return_order_bonus($order_id);
	        }
	
	        /* 如果使用库存，则增加库存 */
	        if ($GLOBALS['_CFG']['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_SHIP){
	            change_order_goods_storage($order['order_id'], false, SDT_SHIP);
	        }
	
	        /* 删除发货单 */
	        del_order_delivery($order_id);
	
	        /* 将订单的商品发货数量更新为 0 */
	        $sql = "UPDATE " . 'ybr_order_goods' . "
	                SET send_number = 0
	                WHERE order_id = '$order_id'";
	        //$GLOBALS['db']->query($sql, 'SILENT');
	        M()->query($sql);
	    }
	    /* 收货确认 */
	    elseif ('receive' == $operation){
	        /* 标记订单为“收货确认”，如果是货到付款，同时修改订单为已付款 */
	        $arr = array('shipping_status' => SS_RECEIVED);
	        $payment = payment_info($order['pay_id']);
	        if ($payment['is_cod']){
	            $arr['pay_status'] = PS_PAYED;
	            $order['pay_status'] = PS_PAYED;
	        }
	        update_order($order_id, $arr);
	        
	        /* 记录log */
        	order_action($order['order_sn'], $order['order_status'], SS_RECEIVED, $order['pay_status'], $action_note);
	    }
	    /* 取消 */
	    elseif ('cancel' == $operation){
	        /* 标记订单为“取消”，记录取消原因 */
	        $cancel_note = isset($_REQUEST['cancel_note']) ? trim($_REQUEST['cancel_note']) : '';
	        $arr = array(
	            'order_status'  => OS_CANCELED,
	            'to_buyer'      => $cancel_note,
	            'pay_status'    => PS_UNPAYED,
	            'pay_time'      => 0,
	            'money_paid'    => 0,
	            'order_amount'  => $order['money_paid']
	        );
	        update_order($order_id, $arr);
	
	        /* todo 处理退款 */
	        if ($order['money_paid'] > 0){
	            $refund_type = $_REQUEST['refund'];
	            $refund_note = $_REQUEST['refund_note'];
	            $OrderModel->order_refund($order, $refund_type, $refund_note);
	        }
			
	        /* 记录log */
        	order_action($order['order_sn'], OS_CANCELED, $order['shipping_status'], PS_UNPAYED, $action_note);
	        
	        /* 如果使用库存，且下订单时减库存，则增加库存 */
	        if ($GLOBALS['_CFG']['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_PLACE){
	            change_order_goods_storage($order_id, false, SDT_PLACE);
	        }
	
	        /* 退还用户余额、积分、红包 */
	        return_user_surplus_integral_bonus($order);	
	       //$this->success("操作成功",U('order/order') . '?order_id=' . $order_id);
	    }
	    /* 设为无效 */
	    elseif ('invalid' == $operation){
	        /* 标记订单为“无效”、“未付款” */
	        update_order($order_id, array('order_status' => OS_INVALID));
			
	        /* 记录log */
        	order_action($order['order_sn'], OS_INVALID, $order['shipping_status'], PS_UNPAYED, $action_note);
	        
	        /* 如果使用库存，且下订单时减库存，则增加库存 */
	        if ($GLOBALS['_CFG']['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_PLACE){
	            change_order_goods_storage($order_id, false, SDT_PLACE);
	        }	        	
	        /* 退货用户余额、积分、红包 */
	        return_user_surplus_integral_bonus($order);
	    }
	    /* 退货 */
	    elseif ('return' == $operation){
	        /* 定义当前时间 */
	        define('GMTIME_UTC', gmtime()); // 获取 UTC 时间戳	
	        /* 过滤数据 */
	        $_REQUEST['refund'] = isset($_REQUEST['refund']) ? $_REQUEST['refund'] : '';
	        $_REQUEST['refund_note'] = isset($_REQUEST['refund_note']) ? $_REQUEST['refund'] : '';
	
	        /* 标记订单为“退货”、“未付款”、“未发货” */
	        $arr = array('order_status'     => OS_RETURNED,
	                     'pay_status'       => PS_UNPAYED,
	                     'shipping_status'  => SS_UNSHIPPED,
	                     'money_paid'       => 0,
	                     'invoice_no'       => '',
	                     'order_amount'     => $order['money_paid']);
	        update_order($order_id, $arr);
	
	        /* todo 处理退款 */
	        if ($order['pay_status'] != PS_UNPAYED){
	            $refund_type = $_REQUEST['refund'];
	            $refund_note = $_REQUEST['refund'];
	            $OrderModel->order_refund($order, $refund_type, $refund_note);
	        }
			
	        /* 记录log */
        	order_action($order['order_sn'], OS_RETURNED, SS_UNSHIPPED, PS_UNPAYED, $action_note);
	        
	        /* 如果订单用户不为空，计算积分，并退回 */
	        if ($order['user_id'] > 0){
	            /* 取得用户信息 */
	            $user 				= 	user_info($order['user_id']);
	
	            $sql 				= 	"SELECT  goods_number, send_number FROM ". ' ybr_order_goods ' . " WHERE order_id = '".$order['order_id']."'";
	
	            $goods_num 			= 	$CommonModel->getRow($sql);
	
	            if($goods_num['goods_number'] == $goods_num['send_number']){
	                /* 计算并退回积分 */
	                $integral 		= 	integral_to_give($order);
	                log_account_change($order['user_id'], 0, 0, (-1) * intval($integral['rank_points']), (-1) * intval($integral['custom_points']), sprintf($_LANG['return_order_gift_integral'], $order['order_sn']));
	            }
	            /* todo 计算并退回红包 */
	            return_order_bonus($order_id);
	        }
	
	        /* 如果使用库存，则增加库存（不论何时减库存都需要） */
	        if ($GLOBALS['_CFG']['use_storage'] == '1'){
	            if ($GLOBALS['_CFG']['stock_dec_time'] == SDT_SHIP){
	                change_order_goods_storage($order['order_id'], false, SDT_SHIP);
	            }
	            elseif ($GLOBALS['_CFG']['stock_dec_time'] == SDT_PLACE){
	                change_order_goods_storage($order['order_id'], false, SDT_PLACE);
	            }
	        }
	
	        /* 退货用户余额、积分、红包 */
	        return_user_surplus_integral_bonus($order);
	
	        /* 获取当前操作员 */
	        $delivery['action_user'] = $_SESSION['admin_name'];
	        /* 添加退货记录 */
	        $delivery_list = array();
	        $sql_delivery = "SELECT * FROM " . 'ybr_delivery_order' . " WHERE status IN (0, 2) AND order_id = " . $order['order_id'];
	        
	        $delivery_list = M()->query($sql_delivery);
	        
	        if ($delivery_list){
	            foreach ($delivery_list as $list){
	                $sql_back = "INSERT INTO " . 'ybr_back_order' 
	                			. " (delivery_sn, order_sn, order_id, add_time, shipping_id, user_id, action_user, consignee, address, Country, province, City, district, sign_building, Email,Zipcode, Tel, Mobile, best_time, postscript, how_oos, insure_fee, shipping_fee, update_time, suppliers_id, return_time, agency_id, invoice_no) VALUES ";
	
	                $sql_back .= " ( '" . $list['delivery_sn'] . "', '" . $list['order_sn'] . "',
	                              '" . $list['order_id'] . "', '" . $list['add_time'] . "',
	                              '" . $list['shipping_id'] . "', '" . $list['user_id'] . "',
	                              '" . $delivery['action_user'] . "', '" . $list['consignee'] . "',
	                              '" . $list['address'] . "', '" . $list['country'] . "', '" . $list['province'] . "',
	                              '" . $list['city'] . "', '" . $list['district'] . "', '" . $list['sign_building'] . "',
	                              '" . $list['email'] . "', '" . $list['zipcode'] . "', '" . $list['tel'] . "',
	                              '" . $list['mobile'] . "', '" . $list['best_time'] . "', '" . $list['postscript'] . "',
	                              '" . $list['how_oos'] . "', '" . $list['insure_fee'] . "',
	                              '" . $list['shipping_fee'] . "', '" . $list['update_time'] . "',
	                              '" . $list['suppliers_id'] . "', '" . GMTIME_UTC . "',
	                              '" . $list['agency_id'] . "', '" . $list['invoice_no'] . "'
	                              )";
	                M()->query($sql_back);
	                $back_id = M()->getLastInsID();
	            	
	                $sql_back_goods = "INSERT INTO " . 'ybr_back_goods' . " (back_id, goods_id, product_id, product_sn, goods_name,goods_sn, is_real, send_number, goods_attr)
	                                   SELECT '$back_id', goods_id, product_id, product_sn, goods_name, goods_sn, is_real, send_number, goods_attr
	                                   FROM " . 'ybr_delivery_goods' . "
	                                   WHERE delivery_id = " . $list['delivery_id'];
	                M()->query($sql_back_goods);
	            }
	        }
			
	        /* 修改订单的发货单状态为退货 */
	        $sql_delivery = "UPDATE " . 'ybr_delivery_order' . " SET status = 1 WHERE status IN (0, 2) AND order_id = " . $order['order_id'];
	        M()->query($sql_delivery);
	
	        /* 将订单的商品发货数量更新为 0 */
	        $sql = "UPDATE " . 'ybr_order_goods' . " SET send_number = 0 WHERE order_id = '$order_id'";
	        M()->query($sql);
	    }
	    elseif ('after_service' == $operation){
	       	/* 记录log */
        	order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], '[' . $_LANG['op_after_service'] . '] ' . $action_note);
	    }
	    else{
	        die('无效的操作');
	    }	
	    /* 操作成功 */	    
		$this->success("操作成功",U("order/order") . '?order_id=' . $order_id);
	}
		
	
	// 快递单列表
	public function delivery_list(){	    		
		/* 获取供货商列表 */
	    $SupplierModel	=	new SupplierModel();
	    $suppliers_list = 	$SupplierModel->get_suppliers_list();
	    $_suppliers_list = array();
	    foreach ($suppliers_list as $value){
	        $_suppliers_list[$value['suppliers_id']] = $value['suppliers_name'];
	    }	    
	    /* 模板赋值 */
	    $this->assign('os_unconfirmed',   OS_UNCONFIRMED);
	    $this->assign('cs_await_pay',     CS_AWAIT_PAY);
	    $this->assign('cs_await_ship',    CS_AWAIT_SHIP);
	    $this->assign('suppliersList',   $_suppliers_list);		    
	    /* 查询 */
	    $sql_delivery_list = get_delivery_list();

	    $param = array(
				'result'=>$sql_delivery_list,					//分页用的数组或sql
				'listvar'=>'deliveryList',		//分页循环变量
				'listRows'=>15,					//每页记录数
				//'parameter'=>'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'=>'content',	    	//ajax更新内容的容器id，不带#
				'pagesId'=>'page',				//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'=>'Order:delivery_list',//ajax更新模板
		);
	    $this->delivery_list_page($param);
	    $this->display();
	}
	
	public function delivery_list_page($param){
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置

	 	// 格式话数据
		$lang_delivery_status	=	L('delivery_status');
	    foreach ($voList AS $key => $value){
	        $voList[$key]['add_time'] = local_date("Y-m-d H:i:s", $value['add_time']);
	        $voList[$key]['update_time'] = local_date("Y-m-d H:i:s", $value['update_time']);
	        if ($value['status'] == 1){
	            $voList[$key]['status_name'] = $lang_delivery_status[1];
	        }
	        elseif ($value['status'] == 2){
	            $voList[$key]['status_name'] = $lang_delivery_status[2];
	        }
	        else{
	        	$voList[$key]['status_name'] = $lang_delivery_status[0];
	        }
	        $voList[$key]['suppliers_name'] = isset($_suppliers_list[$value['suppliers_id']]) ? $_suppliers_list[$value['suppliers_id']] : '';
	    }
	    	    
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
	
	
	/**
	 * 返货单详细信息
	 * 
	 * 
	 */
	public function delivery_info(){
		
		$CommonModel	=	new CommonModel();
		$UserModel		=	new UserModel();		
	    $delivery_id 	= 	intval(trim($_REQUEST['delivery_id']));
	
	    /* 根据发货单id查询发货单信息 */
	    if (!empty($delivery_id)){
	        $delivery_order = delivery_order_info($delivery_id);
	    }
	    else{
	        die('order does not exist');
	    }
	    
	    /* 如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
	    $sql 		= 	"SELECT agency_id FROM " . 'ybr_admin_user' . " WHERE user_id = '" . $_SESSION['admin_id'] . "'";
	    $agency_id 	= 	$CommonModel->getOne($sql);
	    
	    if ($agency_id > 0){
	        if ($delivery_order['agency_id'] != $agency_id){
	            $this->error(L('priv_error'));
	        }	
	        /* 取当前办事处信息 */
	        $sql 			= 	"SELECT agency_name FROM " . 'ybr_agency' . " WHERE agency_id = '$agency_id' LIMIT 0, 1";
	        $agency_name 	= 	$CommonModel->getOne($sql);
	        $delivery_order['agency_name'] = $agency_name;
	    }
	
	    /* 取得用户名 */
	    if ($delivery_order['user_id'] > 0){
	        $user 								= 	user_info($delivery_order['user_id']);
	        if (!empty($user)){
	            $delivery_order['user_name'] 	= 	$user['user_name'];
	        }
	    }
	
	    /* 取得区域名 */
	    $sql 	= 	"SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
	                "'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
	            	"FROM " . 'ybr_order_info' . " AS o " .
	                "LEFT JOIN " . 'ybr_region' . " AS c ON o.country = c.region_id " .
	                "LEFT JOIN " . 'ybr_region' . " AS p ON o.province = p.region_id " .
	                "LEFT JOIN " . 'ybr_region' . " AS t ON o.city = t.region_id " .
	                "LEFT JOIN " . 'ybr_region' . " AS d ON o.district = d.region_id " .
	            	"WHERE o.order_id = '" . $delivery_order['order_id'] . "'";
	    $delivery_order['region'] = $CommonModel->getOne($sql);
	
	    /* 是否保价 */
	    $order['insure_yn'] = empty($order['insure_fee']) ? 0 : 1;
	
	    /* 取得发货单商品 */
	    $goods_sql 		= 	"SELECT * FROM " . 'ybr_delivery_goods' . " WHERE delivery_id = " . $delivery_order['delivery_id'];
	    $goods_list 	= 	$CommonModel->query($goods_sql);
	
	    /* 是否存在实体商品 */
	    $exist_real_goods = 0;
	    if ($goods_list){
	        foreach ($goods_list as $value){
	            if ($value['is_real']){
	                $exist_real_goods++;
	            }
	        }
	    }
	
	    /* 取得订单操作记录 */
	    $act_list 	= 	array();
	    $sql 		= 	"SELECT * FROM " . 'ybr_order_action' 
	    				." WHERE order_id = '" . $delivery_order['order_id'] . "' AND action_place = 1 ORDER BY log_time DESC,action_id DESC";
	    				echo $sql;
	    $res 		= 	$CommonModel->query($sql);
	    $lang_os	=	L('os'); // 订单状态
		$lang_ps	=	L('ps'); // 付款状态
		$lang_ss	=	L('ss'); // 发货状态	
		$lang_ss_admin	=	L('ss_admin'); // 后台发货状态	
		
	    foreach($res as $row){
	    	$row['order_status']    = 	$lang_os[$row['order_status']];
	        $row['pay_status']      = 	$lang_ps[$row['pay_status']];
	        $row['shipping_status'] = 	($row['shipping_status'] == SS_SHIPPED_ING) ? $lang_ss_admin[SS_SHIPPED_ING] : $lang_ss[$row['shipping_status']];
	        $row['action_time']     = 	local_date($GLOBALS['_CFG']['time_format'], $row['log_time']);
	        $act_list[] 			= 	$row;
	    }

	    t($act_list);
	    
	    /* 模板赋值 */
	    $this->assign('action_list', $act_list);
	    $this->assign('delivery_order', $delivery_order);
	    $this->assign('exist_real_goods', $exist_real_goods);
	    $this->assign('goods_list', $goods_list);
	    $this->assign('delivery_id', $delivery_id); // 发货单id
	    $this->assign('action_act', ($delivery_order['status'] == 2) ? 'delivery_ship' : 'delivery_cancel_ship');
		$this->display();
	}
	
	/**
	 * 确认发货
	 * 
	 */
	public function delivery_ship(){
		
		//t($_REQUEST);
		$OrderModel			=	new OrderModel();
		$CommonModel		=	new CommonModel();		
		$UserModel			=	new UserModel();		
		
	    /* 定义当前时间 */
	    define('GMTIME_UTC', gmtime()); // 获取 UTC 时间戳
	
	    /* 取得参数 */
	    $delivery   			= 	array();
	    $order_id   			= 	intval(trim($_REQUEST['order_id']));        // 订单id
	    $delivery_id   			= 	intval(trim($_REQUEST['delivery_id']));     // 发货单id
	    $delivery['invoice_no'] = 	isset($_REQUEST['invoice_no']) ? trim($_REQUEST['invoice_no']) : '';
	    $action_note    		= 	isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
		/* 判断发货单号是否为空 */
	    if(empty($delivery['invoice_no'])){
	    	$this->error("发货单号不能为空");
	    }
	    
	    /* 根据发货单id查询发货单信息 */
	    if (!empty($delivery_id)){
	        $delivery_order = delivery_order_info($delivery_id);
	    }
	    else{
	        die('order does not exist');
	    }
	    	
	    /* 查询订单信息 */
	    $order 					= 	$OrderModel->get_order_goods($order_id);
	    	
	    /* 检查此单发货商品库存缺货情况 */
	    $virtual_goods 			= 	array();
	    $delivery_stock_sql 	= 	"SELECT DG.goods_id, DG.is_real, DG.product_id, SUM(DG.send_number) AS sums, IF(DG.product_id > 0, P.product_number, G.goods_number) AS storage, G.goods_name, DG.send_number
	        						FROM " . 'ybr_delivery_goods' . " AS DG, " . 'ybr_goods' . " AS G, " . 'ybr_products' . " AS P
	        						WHERE DG.goods_id = G.goods_id
	        						AND DG.delivery_id = '$delivery_id'
	        						AND DG.product_id = P.product_id
	        						GROUP BY DG.product_id ";
	
	    $delivery_stock_result = $CommonModel->query($delivery_stock_sql);
		
	    /* 如果商品存在规格就查询规格，如果不存在规格按商品库存查询 */
	    if(!empty($delivery_stock_result)){
	        foreach ($delivery_stock_result as $value){
	        	// 发货商品是否大于库存,库存是否为0
	            if (($value['sums'] > $value['storage'] || $value['storage'] <= 0) && (($GLOBALS['_CFG']['use_storage'] == '1'  && $GLOBALS['_CFG']['stock_dec_time'] == SDT_SHIP) || ($GLOBALS['_CFG']['use_storage'] == '0' && $value['is_real'] == 0))){
	                /* 操作失败 */
	                //$links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
	                //sys_msg(sprintf($_LANG['act_good_vacancy'], $value['goods_name']), 1, $links);
	                $this->error(L('act_good_vacancy'),U('order/delivery_info') . '?delivery_id=' . $delivery_id);
	                break;
	            }
	
	            /* 虚拟商品列表 virtual_card*/
	            if ($value['is_real'] == 0){
	                $virtual_goods[] = array(
	                               'goods_id' => $value['goods_id'],
	                               'goods_name' => $value['goods_name'],
	                               'num' => $value['send_number']
	                               );
	            }
	        }
	    }
	    else{
	        $delivery_stock_sql 	= 	"SELECT DG.goods_id, DG.is_real, SUM(DG.send_number) AS sums, G.goods_number, G.goods_name, DG.send_number
	        							FROM " . 'ybr_delivery_goods' . " AS DG, " . 'ybr_goods' . " AS G
	        							WHERE DG.goods_id = G.goods_id
	        							AND DG.delivery_id = '$delivery_id'
	        							GROUP BY DG.goods_id ";
	        $delivery_stock_result 	= 	$CommonModel->query($delivery_stock_sql);
	        foreach ($delivery_stock_result as $value){
	            if (($value['sums'] > $value['goods_number'] || $value['goods_number'] <= 0) && (($GLOBALS['_CFG']['use_storage'] == '1'  && $GLOBALS['_CFG']['stock_dec_time'] == SDT_SHIP) || ($GLOBALS['_CFG']['use_storage'] == '0' && $value['is_real'] == 0))){
	                /* 操作失败 */
	                //$links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
	                //sys_msg(sprintf($_LANG['act_good_vacancy'], $value['goods_name']), 1, $links);
	                $this->error(L('act_good_vacancy'),U('order/delivery_info') . '?delivery_id=' . $delivery_id);
	                break;
	            }
	
	            /* 虚拟商品列表 virtual_card*/
	            if ($value['is_real'] == 0){
	                $virtual_goods[] = array(
	                               'goods_id' => $value['goods_id'],
	                               'goods_name' => $value['goods_name'],
	                               'num' => $value['send_number']
	                               );
	            }
	        }
	    }
	
	    /* 发货 */
	    /* 处理虚拟卡 商品（虚货） */
	    if (is_array($virtual_goods) && count($virtual_goods) > 0){
	        foreach ($virtual_goods as $virtual_value){
	            virtual_card_shipping($virtual_value,$order['order_sn'], $msg, 'split');
	        }
	    }
	
	    /* 如果使用库存，且发货时减库存，则修改库存 */
	    if ($GLOBALS['_CFG']['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_SHIP){	
	        foreach ($delivery_stock_result as $value){	
	            /* 商品（实货）、超级礼包（实货） */
	            if ($value['is_real'] != 0){
	                //（货品）
	                if (!empty($value['product_id'])){
	                    $minus_stock_sql = "UPDATE " . 'ybr_products' . "
	                                        SET product_number = product_number - " . $value['sums'] . "
	                                        WHERE product_id = " . $value['product_id'];
	                    $CommonModel->query($minus_stock_sql);
	                }
	
	                $minus_stock_sql = "UPDATE " . 'ybr_goods' . "
	                                    SET goods_number = goods_number - " . $value['sums'] . "
	                                    WHERE goods_id = " . $value['goods_id'];
	
	                $CommonModel->query($minus_stock_sql);
	            }
	        }
	    }
	
	    /* 修改发货单信息 */
	    $invoice_no 				= 	str_replace(',', '<br>', $delivery['invoice_no']);
	    $invoice_no 				= 	trim($invoice_no, '<br>');
	    $_delivery['invoice_no'] 	= 	$invoice_no;
	    $_delivery['status'] 		= 	0; // 0，为已发货
	    $query 						= 	$CommonModel->autoExecute('delivery_order', $_delivery, 'UPDATE', "delivery_id = $delivery_id");
	    if (!$query){
	        /* 操作失败 */
	        //$links[] = array('text' => $_LANG['delivery_sn'] . $_LANG['detail'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
	        //sys_msg($_LANG['act_false'], 1, $links);
	        $this->error(L('act_false'),U('order/delivery_info') . '?delivery_id=' . $delivery_id);
	    }
	
	    /* 标记订单为已确认 “已发货” */
	    /* 更新发货时间 */
	    $order_finish 		= 	get_all_delivery_finish($order_id);
	    $shipping_status 	= 	($order_finish == 1) ? SS_SHIPPED : SS_SHIPPED_PART;
	    $arr['shipping_status']     = 	$shipping_status;
	    $arr['shipping_time']       = 	GMTIME_UTC; // 发货时间
	    $arr['invoice_no']          = 	trim($order['invoice_no'] . '<br>' . $invoice_no, '<br>');
	    update_order($order_id, $arr);
	
	    /* 发货单发货记录log */
	    order_action($order['order_sn'], OS_CONFIRMED, $shipping_status, $order['pay_status'], $action_note, null, 1);
	
	    /* 如果当前订单已经全部发货 */
	    if ($order_finish){
	        /* 如果订单用户不为空，计算积分，并发给用户；发红包 */
	        if ($order['user_id'] > 0){
	            /* 取得用户信息 */
	            $user 				= 	user_info($order['user_id']);
	
	            /* 计算并发放积分 */
	            $integral 			= 	integral_to_give($order);
	
	            log_account_change($order['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf(L('order_gift_integral'), $order['order_sn']));
	
	            /* 发放红包 */
	            send_order_bonus($order_id);
	        }
	    }
		// 清除缓存
	    clear_cache();
		$this->success(L('act_ok'),U('order/delivery_info') . '?delivery_id=' . $delivery_id);
	}
	
	/**
	 * 取消发货
	 * Enter description here ...
	 */
	public function delivery_cancel_ship(){
		
		$OrderModel		=	new OrderModel();
		$CommonModel	=	new CommonModel();
		$userModel		=	new UserModel();
		
	    /* 取得参数 */
	    $delivery 		= 	'';
	    $order_id   	= 	intval(trim($_REQUEST['order_id']));        // 订单id
	    $delivery_id   	= 	intval(trim($_REQUEST['delivery_id']));        // 发货单id
	    $delivery['invoice_no'] 	= 	isset($_REQUEST['invoice_no']) ? trim($_REQUEST['invoice_no']) : '';
	    $action_note 	= 	isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
	
	    /* 根据发货单id查询发货单信息 */
	    if (!empty($delivery_id)){
	        $delivery_order = delivery_order_info($delivery_id);
	    }
	    else{
	        die('order does not exist');
	    }
	
	    /* 查询订单信息 */
	    $order 						= 	order_info($order_id);
		
	    /* 取消当前发货单物流单号 */
	    $_delivery['invoice_no'] 	= 	'';
	    $_delivery['status'] 		= 	2;
	    $query 						= 	$CommonModel->autoExecute('delivery_order', $_delivery, 'UPDATE', "delivery_id = $delivery_id");
	    if (!$query){
	        /* 操作失败
	        $links[] = array('text' => $_LANG['delivery_sn'] . $_LANG['detail'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
	        sys_msg($_LANG['act_false'], 1, $links); */
	    	$this->error(L('"act_false"'),U('order/delivery_info') . '?delivery_id=' . $delivery_id);
	        exit;
	    }
	
	    /* 修改定单发货单号 */
	    $invoice_no_order 			= 	explode('<br>', $order['invoice_no']);
	    $invoice_no_delivery 		= 	explode('<br>', $delivery_order['invoice_no']);
	    foreach ($invoice_no_order as $key => $value){
	        $delivery_key 			= 	array_search($value, $invoice_no_delivery);
	        if ($delivery_key !== false){
	            unset($invoice_no_order[$key], $invoice_no_delivery[$delivery_key]);
	            if (count($invoice_no_delivery) == 0){
	                break;
	            }
	        }
	    }
	    $_order['invoice_no'] 		= 	implode('<br>', $invoice_no_order);
	
	    /* 更新配送状态 */
	    $order_finish 				= 	get_all_delivery_finish($order_id);
	    $shipping_status 			= 	($order_finish == -1) ? SS_SHIPPED_PART : SS_SHIPPED_ING;
	    $arr['shipping_status']     = 	$shipping_status;
	    if ($shipping_status == SS_SHIPPED_ING){
	        $arr['shipping_time']   = 	''; // 发货时间
	    }
	    $arr['invoice_no']          = 	$_order['invoice_no'];
	    update_order($order_id, $arr);
	
	    /* 发货单取消发货记录log */
	    order_action($order['order_sn'], $order['order_status'], $shipping_status, $order['pay_status'], $action_note, null, 1);
	
	    /* 如果使用库存，则增加库存 */
	    if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_SHIP){
	        // 检查此单发货商品数量
	        $virtual_goods 			= 	array();
	        $delivery_stock_sql 	= 	"SELECT DG.goods_id, DG.product_id, DG.is_real, SUM(DG.send_number) AS sums
	            						FROM " . 'ybr_delivery_goods' . " AS DG
	            						WHERE DG.delivery_id = '$delivery_id'
	            						GROUP BY DG.goods_id ";
	        $delivery_stock_result 	= 	$CommonModel->query($delivery_stock_sql);
	        foreach ($delivery_stock_result as $key => $value){
	            /* 虚拟商品 */
	            if ($value['is_real'] == 0){
	                continue;
	            }	
	            //（货品）
	            if (!empty($value['product_id'])){
	                $minus_stock_sql = "UPDATE " . 'ybr_products' . "
	                                    SET product_number = product_number + " . $value['sums'] . "
	                                    WHERE product_id = " . $value['product_id'];
	                $CommonModel->query($minus_stock_sql);
	            }
	
	            $minus_stock_sql = "UPDATE " . 'ybr_goods' . "
	                                SET goods_number = goods_number + " . $value['sums'] . "
	                                WHERE goods_id = " . $value['goods_id'];
	            $CommonModel->query($minus_stock_sql);
	        }
	    }
	
	    /* 发货单全退回时，退回其它 */
	    if ($order['order_status'] == SS_SHIPPED_ING){
	        /* 如果订单用户不为空，计算积分，并退回 */
	        if ($order['user_id'] > 0){
	            /* 取得用户信息 */
	            $user 					= 	user_info($order['user_id']);
	
	            /* 计算并退回积分 */
	            $integral 				= 	integral_to_give($order);
	            log_account_change($order['user_id'], 0, 0, (-1) * intval($integral['rank_points']), (-1) * intval($integral['custom_points']), sprintf(L('return_order_gift_integral'), $order['order_sn']));
	
	            /* todo 计算并退回红包 */
	            return_order_bonus($order_id);
	        }
	    }	
	    /* 清除缓存 */
	    clear_cache();	
	    /* 操作成功 
	    $links[] = array('text' => $_LANG['delivery_sn'] . $_LANG['detail'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
	    sys_msg($_LANG['act_ok'], 0, $links);*/
		$this->success(L('act_ok'),U('order/delivery_info') . '?delivery_id=' . $delivery_id);
	}
	
	/**
	 * 打印订单
	 * 
	 */
	public function print_order(){}
	
	/**
	 * 编辑订单信息
	 * 
	 */
	public function edit_order(){		
		
		$CommonModel		=	new CommonModel();
		$UserModel			=	new UserModel();
		$OrderModel			=	new OrderModel();
		
	    /* 取得参数 order_id */
	    $order_id 			= 	isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
	    $this->assign('order_id', $order_id);
	
	    /* 取得参数 step */
	    $step_list 			= 	array('user', 'goods', 'consignee', 'shipping', 'payment', 'other', 'money');
	    $step 				= 	isset($_GET['step']) && in_array($_GET['step'], $step_list) ? $_GET['step'] : 'user';
	    $this->assign('step', $step);
		/* 取得参数 act */
	    $act 				= 	$_GET['act'];
		$this->assign('step_act', $act);
	    
	    
	    /* 取得订单信息 */
	    if ($order_id > 0){
	        $order 			= 	order_info($order_id);
	
	        /* 发货单格式化 */
	        $order['invoice_no'] = str_replace('<br>', ',', $order['invoice_no']);
	
	        /* 如果已发货，就不能修改订单了（配送方式和发货单号除外） */
	        if ($order['shipping_status'] == SS_SHIPPED || $order['shipping_status'] == SS_RECEIVED){
	            if ($step != 'shipping'){
	                //sys_msg($_LANG['cannot_edit_order_shipped']);
	                $this->error(L('cannot_edit_order_shipped'));
	            }
	            else{
	                $step 	= 	'invoice';
	                $this->assign('step', $step);
	            }
	        }	
	        $this->assign('order', $order);
	    }
	    else{
	        if ($act != 'add' || $step != 'user'){
	            die('invalid params');
	        }
	    }
	
	    /* 选择会员 */
	    if ('user' == $step){
	        // 无操作
	    }
	
	    /* 增删改商品 */
	    elseif ('goods' == $step){
	        /* 取得订单商品 */
	        $goods_list = order_goods($order_id);
	        if (!empty($goods_list)){
	            foreach ($goods_list AS $key => $goods){
	                /* 计算属性数 */
	                $attr = $goods['goods_attr'];
	                if ($attr == ''){
	                    $goods_list[$key]['rows'] = 1;
	                }
	                else{
	                    $goods_list[$key]['rows'] = count(explode(chr(13), $attr));
	                }
	            }
	        }	
	        $this->assign('goods_list', $goods_list);
			/* 取得商品总金额 */
	        $this->assign('goods_amount', order_amount($order_id));
	    }
	
	    // 设置收货人
	    elseif ('consignee' == $step){
	        /* 查询是否存在实体商品 */
	        $exist_real_goods 	=	 exist_real_goods($order_id);	        
	        $this->assign('exist_real_goods', $exist_real_goods);
	
	        /* 取得收货地址列表 */
	        if ($order['user_id'] > 0){
	            $this->assign('address_list', address_list($order['user_id']));
	
	            $address_id = isset($_REQUEST['address_id']) ? intval($_REQUEST['address_id']) : 0;
	            if ($address_id > 0){
	                $address = address_info($address_id);
	                if ($address){
	                    $order['consignee']     = $address['consignee'];
	                    $order['country']       = $address['country'];
	                    $order['province']      = $address['province'];
	                    $order['city']          = $address['city'];
	                    $order['district']      = $address['district'];
	                    $order['email']         = $address['email'];
	                    $order['address']       = $address['address'];
	                    $order['zipcode']       = $address['zipcode'];
	                    $order['tel']           = $address['tel'];
	                    $order['mobile']        = $address['mobile'];
	                    $order['sign_building'] = $address['sign_building'];
	                    $order['best_time']     = $address['best_time'];
	                    $this->assign('order', $order);
	                }
	            }
	        }
	
	        if ($exist_real_goods){
	            /* 取得国家 */
	            $this->assign('country_list', get_regions());
	            if ($order['country'] > 0){
	                /* 取得省份 */
	                $this->assign('province_list', get_regions(1, $order['country']));
	                if ($order['province'] > 0){
	                    /* 取得城市 */
	                    $this->assign('city_list', get_regions(2, $order['province']));
	                    if ($order['city'] > 0){
	                        /* 取得区域 */
	                        $this->assign('district_list', get_regions(3, $order['city']));
	                    }
	                }
	            }
	        }
	    }
	
	    // 选择配送方式
	    elseif ('shipping' == $step){
	        /* 如果不存在实体商品 */
	        if (!exist_real_goods($order_id)){
	            die ('Hacking Attemp');
	        }
	
	        /* 取得可用的配送方式列表 */
	        $region_id_list = array(
	            $order['country'], $order['province'], $order['city'], $order['district']
	        );
	        $shipping_list = available_shipping_list($region_id_list);
	
	        /* 取得配送费用 */
	        $total = order_weight_price($order_id);
	        foreach ($shipping_list AS $key => $shipping){
	            $shipping_fee = shipping_fee($shipping['shipping_code'],
	                unserialize($shipping['configure']), $total['weight'], $total['amount'], $total['number']);
	            $shipping_list[$key]['shipping_fee'] = $shipping_fee;
	            $shipping_list[$key]['format_shipping_fee'] = price_format($shipping_fee);
	            $shipping_list[$key]['free_money'] = price_format($shipping['configure']['free_money']);
	        }
	        $this->assign('shipping_list', $shipping_list);
	    }
	
	    // 选择支付方式
	    elseif ('payment' == $step){
	    		    	
	        /* 取得可用的支付方式列表 */
	        if (exist_real_goods($order_id)){
	            /* 存在实体商品 */
	            $region_id_list = array(
	                $order['country'], $order['province'], $order['city'], $order['district']
	            );
	            $shipping_area 	= 	shipping_area_info($order['shipping_id'], $region_id_list);	            
	            $pay_fee 		= 	($shipping_area['support_cod'] == 1) ? $shipping_area['pay_fee'] : 0;
	
	            $payment_list 	= 	available_payment_list($shipping_area['support_cod'], $pay_fee);
	        }
	        else{
	            /* 不存在实体商品 */
	            $payment_list 	= 	available_payment_list(false);
	        }
	
	        /* 过滤掉使用余额支付 */
	        foreach ($payment_list as $key => $payment){
	            if ($payment['pay_code'] == 'balance'){
	                unset($payment_list[$key]);
	            }
	        }
	        $this->assign('payment_list', $payment_list);
	    }
	
	    // 选择包装、贺卡
	    elseif ('other' == $step){
	        /* 查询是否存在实体商品 */
	        $exist_real_goods 	= 	exist_real_goods($order_id);
	        $this->assign('exist_real_goods', $exist_real_goods);
	
	        if ($exist_real_goods){
	            /* 取得包装列表 */
	            $this->assign('pack_list', pack_list());	
	            /* 取得贺卡列表 */
	            $this->assign('card_list', card_list());
	        }
	    }
	
	    // 费用
	    elseif ('money' == $step){
	        /* 查询是否存在实体商品 */
	        $exist_real_goods = exist_real_goods($order_id);
	        $this->assign('exist_real_goods', $exist_real_goods);
		
	        /* 取得用户信息 */
	        if ($order['user_id'] > 0){
	            $user 					= 	user_info($order['user_id']);
	
	            /* 计算可用余额 */
	            $this->assign('available_user_money', $order['surplus'] + $user['user_money']);
	
	            /* 计算可用积分 */
	            $this->assign('available_pay_points', $order['integral'] + $user['pay_points']);
	
	            /* 取得用户可用红包 */
	            $user_bonus 			= 	user_bonus($order['user_id'], $order['goods_amount']);
	            if ($order['bonus_id'] > 0){
	                $bonus 				= 	bonus_info($order['bonus_id']);
	                $user_bonus[] 		= 	$bonus;
	            }
	            $this->assign('available_bonus', $user_bonus);
	        }
	    }
	
	    // 发货后修改配送方式和发货单号
	    elseif ('invoice' == $step){
	        /* 如果不存在实体商品 */
	        if (!exist_real_goods($order_id)){
	            die ('Hacking Attemp');
	        }
	
	        /* 取得可用的配送方式列表 */
	        $region_id_list = array(
	            $order['country'], $order['province'], $order['city'], $order['district']
	        );
	        $shipping_list 	= 	available_shipping_list($region_id_list);
	
	//        /* 取得配送费用 */
	//        $total = order_weight_price($order_id);
	//        foreach ($shipping_list AS $key => $shipping)
	//        {
	//            $shipping_fee = shipping_fee($shipping['shipping_code'],
	//                unserialize($shipping['configure']), $total['weight'], $total['amount'], $total['number']);
	//            $shipping_list[$key]['shipping_fee'] = $shipping_fee;
	//            $shipping_list[$key]['format_shipping_fee'] = price_format($shipping_fee);
	//            $shipping_list[$key]['free_money'] = price_format($shipping['configure']['free_money']);
	//        }
	        $this->assign('shipping_list', $shipping_list);
	    }
	
		$this->display();
	}
	
	/**
	 * 处理编辑订单结果
	 * 
	 * 
	 */
	public function step_post(){
		
		t($_REQUEST);
		
		$CommonModel	=	new CommonModel();
		
	    /* 取得参数 step */
	    $step_list 		= 	array('user', 'edit_goods', 'add_goods', 'goods', 'consignee', 'shipping', 'payment', 'other', 'money', 'invoice');
	    $step 			= 	isset($_REQUEST['step']) && in_array($_REQUEST['step'], $step_list) ? $_REQUEST['step'] : 'user';
	
	    /* 取得参数 order_id */
	    $order_id 		= 	isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : 0;
	    if ($order_id > 0){
	        $old_order 	= 	order_info($order_id);
	    }
	
	    /* 取得参数 step_act 添加还是编辑 */
	    $step_act 		= 	isset($_REQUEST['step_act']) ? $_REQUEST['step_act'] : 'add';
	
	    /* 插入订单信息 */
	    if ('user' == $step){
	        /* 取得参数：user_id */
	        $user_id = ($_POST['anonymous'] == 1) ? 0 : intval($_POST['user']);
	
	        /* 插入新订单，状态为无效 */
	        $order = array(
	            'user_id'           => $user_id,
	            'add_time'          => gmtime(),
	            'order_status'      => OS_INVALID,
	            'shipping_status'   => SS_UNSHIPPED,
	            'pay_status'        => PS_UNPAYED,
	            'from_ad'           => 0,
	            'referer'           => L('admin')
	        );
	
	    	$order['order_sn'] 	= 	get_order_sn();
            if ($CommonModel->autoExecute('order_info', $order, 'INSERT', '')){
                break;
            }
            else{
                if ($CommonModel->getError()){
                    die($CommonModel->getError());
                }
            }
        	
	        $order_id = $CommonModel->insert_id();
	
	        /* todo 记录日志 */
	        admin_log($order['order_sn'], 'add', 'order');
	
	        /* 插入 pay_log */
	        $sql = 'INSERT INTO ' . 'ybr_pay_log' . " (order_id, order_amount, order_type, is_paid)" .
	                " VALUES ('$order_id', 0, '" . PAY_ORDER . "', 0)";
	        $CommonModel->query($sql);
	
	        /* 下一步 */
	        // ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
	        $this->redirect('/order/' . $step_act . '?order_id=' . $order_id . '&step=goods');
	        exit;
	    }
	    /* 编辑商品信息 */
	    elseif ('edit_goods' == $step){
	        if (isset($_POST['rec_id'])){
	            foreach ($_POST['rec_id'] AS $key => $rec_id){
	              	$sql 	= 	"SELECT goods_number ".
	                	      	'FROM ' . 'ybr_goods' .
	                    	  	"WHERE goods_id =".$_POST['goods_id'][$key];
	               	/* 取得参数 */
	              	$goods_price 		= 	floatval($_POST['goods_price'][$key]);
	              	$goods_number 		= 	intval($_POST['goods_number'][$key]);
	              	$goods_attr 		= 	$_POST['goods_attr'][$key];
	              	$product_id 		= 	intval($_POST['product_id'][$key]);
	              	if($product_id){	
	                	$sql 			= 	"SELECT product_number " . 'FROM ' . 'ybr_products' . " WHERE product_id =".$_POST['product_id'][$key];
	              	}
	              	$goods_number_all 	= 	$CommonModel->getOne($sql);
	            	  if($goods_number_all >= $goods_number){
	                /* 修改 */
		                $sql 			= 	"UPDATE " . 'ybr_order_goods' .
	    	                    			" SET goods_price = '$goods_price', " .
	        	                			"goods_number = '$goods_number', " .
	            	            			"goods_attr = '$goods_attr' " .
	                	        			"WHERE rec_id = '$rec_id' LIMIT 1";
		                $CommonModel->query($sql);
	              	}
	              	else{
	              		//sys_msg($_LANG['goods_num_err']);
	              		$this->display_message(L('goods_num_err'));
	              	}
	            }
	
	            /* 更新商品总金额和订单总金额 */
	            $goods_amount 		= 	order_amount($order_id);
	            update_order($order_id, array('goods_amount' => $goods_amount));
	            update_order_amount($order_id);
	
	            /* 更新 pay_log */
	            update_pay_log($order_id);
	
	            /* todo 记录日志 */
	            $sn 		= 	$old_order['order_sn'];
	            $new_order 	= 	order_info($order_id);
	            if ($old_order['total_fee'] != $new_order['total_fee']){
	                $sn 	.= 	',' . sprintf( L('order_amount_change'), $old_order['total_fee'], $new_order['total_fee']);
	            }
	            admin_log($sn, 'edit', 'order');
	        }
	
	        /* 跳回订单商品 */
	        //ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
	        $this->redirect("/order/" . $step_act . '?order_id=' . $order_id . '&step=goods');
	        exit;
	    }
	    /* 添加商品 */
	    elseif ('add_goods' == $step){
	        /* 取得参数 */
	        $goods_id 		= 	intval($_POST['goodslist']);
	        $goods_price 	= 	$_POST['add_price'] != 'user_input' ? floatval($_POST['add_price']) : floatval($_POST['input_price']);
	        $goods_attr 	= 	'0';
	        for ($i = 0; $i < $_POST['spec_count']; $i++){
	            if (is_array($_POST['spec_' . $i])){
	                $temp_array 		= 	$_POST['spec_' . $i];
	                $temp_array_count 	= 	count($_POST['spec_' . $i]);
	                for ($j = 0; $j < $temp_array_count; $j++){
	                    if($temp_array[$j]!==NULL){
	                        $goods_attr .= 	',' . $temp_array[$j];
	                    }
	                }
	            }
	            else{
	                if($_POST['spec_' . $i]!==NULL){
	                    $goods_attr 	.=	 ',' . $_POST['spec_' . $i];
	                }
	            }
	        }
	        $goods_number 				= 	$_POST['add_number'];
	        $attr_list 					= 	$goods_attr;
	
	        $goods_attr 				= 	explode(',',$goods_attr);
	        $k   						=   array_search(0,$goods_attr);
	        unset($goods_attr[$k]);	
	
	        $sql 						= 	"SELECT attr_value " . 'FROM ' . 'ybr_goods_attr' . "WHERE goods_attr_id in($attr_list)";
	       	$res 						= 	$CommonModel->query($sql);
	       	foreach($res as $row){
	       		$attr_value[] 			= 	$row['attr_value'];
	       	}
	
	        $attr_value 				= 	implode(",",$attr_value);
	
	        $sql 						= 	"SELECT * FROM " .'ybr_products' . " WHERE goods_id = '$goods_id' LIMIT 0, 1";
	        $prod 						= 	$CommonModel->getRow($sql);
	
	
	        if (is_spec($goods_attr) && !empty($prod)){
	            $product_info 			= 	get_products_info($_REQUEST['goodslist'], $goods_attr);
	        }
	
	        //商品存在规格 是货品 检查该货品库存
	        if (is_spec($goods_attr) && !empty($prod)){
	            if (!empty($goods_attr)){
	                /* 取规格的货品库存 */
	                if ($goods_number > $product_info['product_number']){
	                    $url = "order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods";	
	                    echo '<a href="'.$url.'">' . L('goods_num_err') .'</a>';
	                    exit;	
	                    return false;
	                }
	            }
	        }
	
	        if(is_spec($goods_attr) && !empty($prod)){
	        /* 插入订单商品 */
	            $sql 	= 	"INSERT INTO " . 'ybr_order_goods' .
	                        "(order_id, goods_id, goods_name, goods_sn, product_id, goods_number, market_price, " .
	                        "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id) " .
	                    	"SELECT '$order_id', goods_id, goods_name, goods_sn, " .$product_info['product_id'].", ".
	                        "'$goods_number', market_price, '$goods_price', '" .$attr_value . "', " .
	                        "is_real, extension_code, 0, 0 , '".implode(',',$goods_attr)."' " .
	                    	"FROM " . 'ybr_goods' .
	                    	" WHERE goods_id = '$goods_id' LIMIT 1";
	        }
	        else{
	             $sql 	= 	"INSERT INTO " . 'ybr_order_goods' .
	                    	" (order_id, goods_id, goods_name, goods_sn, " .
	                    	"goods_number, market_price, goods_price, goods_attr, " .
	                    	"is_real, extension_code, parent_id, is_gift)" .
	                		"SELECT '$order_id', goods_id, goods_name, goods_sn, " .
	                    	"'$goods_number', market_price, '$goods_price', '" . $attr_value. "', " .
	                    	"is_real, extension_code, 0, 0 " .
	                		"FROM " . 'ybr_goods' .
	                		" WHERE goods_id = '$goods_id' LIMIT 1";
	        }
	        $CommonModel->query($sql);
	
	        /* 如果使用库存，且下订单时减库存，则修改库存 */
	        if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_PLACE){	
	            //（货品）
	            if (!empty($product_info['product_id'])){
	                $sql 	= 	"UPDATE " . 'ybr_products' . " SET product_number = product_number - " . $goods_number . " WHERE product_id = " . $product_info['product_id'];	
	                $CommonModel->query($sql);
	            }
	            	
	            $sql 		= 	"UPDATE " . 'ybr_goods' . " SET `goods_number` = goods_number - '" . $goods_number . "' " . " WHERE `goods_id` = '" . $goods_id . "' LIMIT 1";
	            $CommonModel->query($sql);
	        }
	
	        /* 更新商品总金额和订单总金额 */
	        update_order($order_id, array('goods_amount' => order_amount($order_id)));
	        update_order_amount($order_id);
	
	        /* 更新 pay_log */
	        update_pay_log($order_id);
	
	        /* todo 记录日志 */
	        $sn 		= 	$old_order['order_sn'];
	        $new_order 	= 	order_info($order_id);
	        if ($old_order['total_fee'] != $new_order['total_fee']){
	            $sn 	.= 	',' . sprintf( L('order_amount_change') , $old_order['total_fee'], $new_order['total_fee']);
	        }
	        admin_log($sn, 'edit', 'order');
	
	        /* 跳回订单商品 */
	        //ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
	        $this->redirect("/order/" . $step_act . '?order_id=' . $order_id . '&step=goods');
	        exit;
	    }
	    /* 商品 */
	    elseif ('goods' == $step){
	        /* 下一步 */
	        if (isset($_POST['next'])){
	            //ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=consignee\n");
	            $this->redirect('/order/' . $step_act . '?order_id=' . $order_id . '&step=consignee');
	            exit;
	        }
	        /* 完成 */
	        elseif (isset($_POST['finish'])){
	            /* 初始化提示信息和链接 */
	            $msgs   	= 	array();
	            $links  	= 	array();
	
	            /* 如果已付款，检查金额是否变动，并执行相应操作 */
	            $order 		= 	order_info($order_id);
	            handle_order_money_change($order, $msgs, $links);
	
	            /* 显示提示信息 */
	            if (!empty($msgs)){
	                //sys_msg(join(chr(13), $msgs), 0, $links);
	                $this->display_message(join(chr(13), $msgs), 0, $links);
	            }
	            else{
	                /* 跳转到订单详情 */
	                //ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
	                $this->redirect('order/order' . '?order_id=' . $order_id);
	                exit;
	            }
	        }
	    }
	    /* 保存收货人信息 */
	    elseif ('consignee' == $step){
	        /* 保存订单 */
	        $order 				= 	$_POST;
	        $order['agency_id'] = 	get_agency_by_regions(array($order['country'], $order['province'], $order['city'], $order['district']));
	        update_order($order_id, $order);
	
	        /* 该订单所属办事处是否变化 */
	        $agency_changed 	= 	$old_order['agency_id'] != $order['agency_id'];
	
	        /* todo 记录日志 */
	        $sn 				= 	$old_order['order_sn'];
	        admin_log($sn, 'edit', 'order');
	
	        if (isset($_POST['next'])){
	            /* 下一步 */
	            if (exist_real_goods($order_id)){
	                /* 存在实体商品，去配送方式 */
	                //ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=shipping\n");
	                $this->redirect('order/' . $step_act . '?order_id=' . $order_id . '&step=shipping');
	                exit;
	            }
	            else{
	                /* 不存在实体商品，去支付方式 */
	                //ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=payment\n");
	                $this->redirect('order/' . $step_act . '?order_id=' . $order_id . '&step=payment');
	                exit;
	            }
	        }
	        elseif (isset($_POST['finish'])){
	            /* 如果是编辑且存在实体商品，检查收货人地区的改变是否影响原来选的配送 */
	            if ('edit' == $step_act && exist_real_goods($order_id)){
	                $order = order_info($order_id);
	
	                /* 取得可用配送方式 */
	                $region_id_list = array(
	                    $order['country'], $order['province'], $order['city'], $order['district']
	                );
	                $shipping_list 	= 	available_shipping_list($region_id_list);
	
	                /* 判断订单的配送是否在可用配送之内 */
	                $exist = false;
	                foreach ($shipping_list AS $shipping){
	                    if ($shipping['shipping_id'] == $order['shipping_id']){
	                        $exist 	= 	true;
	                        break;
	                    }
	                }
	
	                /* 如果不在可用配送之内，提示用户去修改配送 */
	                if (!$exist){
	                    // 修改配送为空，配送费和保价费为0
	                    update_order($order_id, array('shipping_id' => 0, 'shipping_name' => ''));
	                    $lang_step	=	L('step');	                    
	                    $links[] 	= 	array('text' => $lang_step['shipping'], 'href' => 'order.php?act=edit&order_id=' . $order_id . '&step=shipping');
	                    //sys_msg($_LANG['continue_shipping'], 1, $links);
	                    $this->display_message($_LANG['continue_shipping'], 1, $links);
	                }
	            }
	
	            /* 完成 */
	            if ($agency_changed){
	                //ecs_header("Location: order.php?act=list\n");
	                $this->redirect('/order/order_list');
	            }
	            else{
	                //ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
	                $this->redirect('/order/order' . "?order_id=" . $order_id );
	            }
	            exit;
	        }
	    }
	    /* 保存配送信息 */
	    elseif ('shipping' == $step){
	        /* 如果不存在实体商品，退出 */
	        if (!exist_real_goods($order_id)){
	            die ('Hacking Attemp');
	        }
	
	        /* 取得订单信息 */
	        $order_info 	= 	order_info($order_id);
	        $region_id_list = 	array($order_info['country'], $order_info['province'], $order_info['city'], $order_info['district']);
	
	        /* 保存订单 */
	        $shipping_id 	= 	$_POST['shipping'];
	        $shipping 		= 	shipping_area_info($shipping_id, $region_id_list);
	        $weight_amount 	= 	order_weight_price($order_id);
	        $shipping_fee 	= 	shipping_fee($shipping['shipping_code'], $shipping['configure'], $weight_amount['weight'], $weight_amount['amount'], $weight_amount['number']);
	        $order 			= 	array(
	            'shipping_id' 	=> $shipping_id,
	            'shipping_name' => addslashes($shipping['shipping_name']),
	            'shipping_fee' 	=> $shipping_fee
	        );
	
	        if (isset($_POST['insure'])){
	            /* 计算保价费 */
	            $order['insure_fee'] = shipping_insure_fee($shipping['shipping_code'], order_amount($order_id), $shipping['insure']);
	        }
	        else{
	            $order['insure_fee'] = 0;
	        }
	        update_order($order_id, $order);
	        update_order_amount($order_id);
	
	        /* 更新 pay_log */
	        update_pay_log($order_id);
	
	        /* 清除首页缓存：发货单查询 
	        clear_cache_files('index.dwt');*/
	
	        /* todo 记录日志 */
	        $sn 			= 	$old_order['order_sn'];
	        $new_order	 	= 	order_info($order_id);
	        if ($old_order['total_fee'] != $new_order['total_fee']){
	            $sn .= ',' . sprintf( L('order_amount_change') , $old_order['total_fee'], $new_order['total_fee']);
	        }
	        admin_log($sn, 'edit', 'order');
	
	        if (isset($_POST['next'])){
	            /* 下一步 */
	            //ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=payment\n");
	            $this->redirect('order/' . $step_act . '?order_id=' . $order_id . '&step=payment' );
	            exit;
	        }
	        elseif (isset($_POST['finish'])){
	            /* 初始化提示信息和链接 */
	            $msgs   	= 	array();
	            $links 	 	= 	array();
	
	            /* 如果已付款，检查金额是否变动，并执行相应操作 */
	            $order 		= 	order_info($order_id);
	            handle_order_money_change($order, $msgs, $links);
	
	            /* 如果是编辑且配送不支持货到付款且原支付方式是货到付款 */
	            if ('edit' == $step_act && $shipping['support_cod'] == 0){
	                $payment = payment_info($order['pay_id']);
	                if ($payment['is_cod'] == 1){
	                    /* 修改支付为空 */
	                    update_order($order_id, array('pay_id' => 0, 'pay_name' => ''));
	                    $msgs[]     = 	L('continue_payment');
	                    $links[]    = 	array('text' => $_LANG['step']['payment'], 'href' => 'order.php?act=' . $step_act . '&order_id=' . $order_id . '&step=payment');
	                }
	            }
	
	            /* 显示提示信息 */
	            if (!empty($msgs)){
	                //sys_msg(join(chr(13), $msgs), 0, $links);
	                $this->display_message(join(chr(13), $msgs), 0, $links);
	            }
	            else{
	                /* 完成 */
	                //ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
	                $this->redirect('/order/order' . '?order_id=' . $order_id);
	                exit;
	            }
	        }
	    }
	    /* 保存支付信息 */
	    elseif ('payment' == $step){
	        /* 取得支付信息 */
	        $pay_id 		= 	$_POST['payment'];
	        $payment 		= 	payment_info($pay_id);
	
	        /* 计算支付费用 */
	        $order_amount 	= 	order_amount($order_id);
	        if ($payment['is_cod'] == 1){
	            $order 			= 	order_info($order_id);
	            $region_id_list = 	array(
	                $order['country'], $order['province'], $order['city'], $order['district']
	            );
	            $shipping 		= 	shipping_area_info($order['shipping_id'], $region_id_list);
	            $pay_fee 		= 	pay_fee($pay_id, $order_amount, $shipping['pay_fee']);
	        }
	        else{
	            $pay_fee 		= 	pay_fee($pay_id, $order_amount);
	        }
	
	        /* 保存订单 */
	        $order 				= 	array(
	            'pay_id' 	=> $pay_id,
	            'pay_name' 	=> addslashes($payment['pay_name']),
	            'pay_fee' 	=> $pay_fee
	        );
	        update_order($order_id, $order);
	        update_order_amount($order_id);
	
	        /* 更新 pay_log */
	        update_pay_log($order_id);
	
	        /* todo 记录日志 */
	        $sn 			= 	$old_order['order_sn'];
	        $new_order 		= 	order_info($order_id);
	        if ($old_order['total_fee'] != $new_order['total_fee']){
	            $sn 		.= 	',' . sprintf( L('order_amount_change'), $old_order['total_fee'], $new_order['total_fee']);
	        }
	        admin_log($sn, 'edit', 'order');
	
	        if (isset($_POST['next'])){
	            /* 下一步 */
	            //ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=other\n");
	            $this->redirect('/order/' . $step_act . '?order_id=' . $order_id . '&step=other');
	            exit;
	        }
	        elseif (isset($_POST['finish'])){
	            /* 初始化提示信息和链接 */
	            $msgs   	= 	array();
	            $links  	= 	array();
	
	            /* 如果已付款，检查金额是否变动，并执行相应操作 */
	            $order 		= 	order_info($order_id);
	            handle_order_money_change($order, $msgs, $links);
	
	            /* 显示提示信息 */
	            if (!empty($msgs)){
	                //sys_msg(join(chr(13), $msgs), 0, $links);
	                $this->display_message(join(chr(13), $msgs), 0, $links);
	            }
	            else{
	                /* 完成 */
	                //ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
	                $this->redirect("/order/order" . '?order_id=' . $order_id);
	                exit;
	            }
	        }
	    }
	    elseif ('other' == $step){
	        /* 保存订单 */
	        $order = array();
	        if (isset($_POST['pack']) && $_POST['pack'] > 0){
	            $pack               = 	pack_info($_POST['pack']);
	            $order['pack_id']   = 	$pack['pack_id'];
	            $order['pack_name'] = 	addslashes($pack['pack_name']);
	            $order['pack_fee']  = 	$pack['pack_fee'];
	        }
	        else{
	            $order['pack_id']   = 	0;
	            $order['pack_name'] = 	'';
	            $order['pack_fee']  = 	0;
	        }
	        if (isset($_POST['card']) && $_POST['card'] > 0){
	            $card               	= 	card_info($_POST['card']);
	            $order['card_id']   	= 	$card['card_id'];
	            $order['card_name'] 	= 	addslashes($card['card_name']);
	            $order['card_fee']  	= 	$card['card_fee'];
	            $order['card_message'] 	= 	$_POST['card_message'];
	        }
	        else{
	            $order['card_id']   	= 	0;
	            $order['card_name'] 	= 	'';
	            $order['card_fee']  	= 	0;
	            $order['card_message'] 	= 	'';
	        }
	        $order['inv_type']      	= 	$_POST['inv_type'];
	        $order['inv_payee']     	= 	$_POST['inv_payee'];
	        $order['inv_content']   	= 	$_POST['inv_content'];
	        $order['how_oos']       	= 	$_POST['how_oos'];
	        $order['postscript']    	= 	$_POST['postscript'];
	        $order['to_buyer']      	= 	$_POST['to_buyer'];
	        update_order($order_id, $order);
	        update_order_amount($order_id);
	
	        /* 更新 pay_log */
	        update_pay_log($order_id);
	
	        /* todo 记录日志 */
	        $sn 		= 	$old_order['order_sn'];
	        admin_log($sn, 'edit', 'order');
	
	        if (isset($_POST['next'])){
	            /* 下一步 */
	            //ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=money\n");
	            $this->redirect('/order/' . $step_act . '?order_id=' . $order_id . '&step=money');
	            exit;
	        }
	        elseif (isset($_POST['finish'])){
	            /* 完成 */
	            //ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
	            $this->redirect('/order/order' . '?order_id=' . $order_id . '&step=money');
	            exit;
	        }
	    }
	    elseif ('money' == $step){
	        /* 取得订单信息 */
	        $old_order = order_info($order_id);
	        
	        if ($old_order['user_id'] > 0){
	            /* 取得用户信息 */
	            $user 				= 	user_info($old_order['user_id']);
	        }
	
	        /* 保存信息 */
	        $order['goods_amount']  = 	$old_order['goods_amount'];
	        $order['discount']      = 	isset($_POST['discount']) && floatval($_POST['discount']) >= 0 ? round(floatval($_POST['discount']), 2) : 0;
	        $order['tax']           = 	round(floatval($_POST['tax']), 2);
	        $order['shipping_fee']  = 	isset($_POST['shipping_fee']) && floatval($_POST['shipping_fee']) >= 0 ? round(floatval($_POST['shipping_fee']), 2) : 0;
	        $order['insure_fee']    = 	isset($_POST['insure_fee']) && floatval($_POST['insure_fee']) >= 0 ? round(floatval($_POST['insure_fee']), 2) : 0;
	        $order['pay_fee']       = 	floatval($_POST['pay_fee']) >= 0 ? round(floatval($_POST['pay_fee']), 2) : 0;
	        $order['pack_fee']      = 	isset($_POST['pack_fee']) && floatval($_POST['pack_fee']) >= 0 ? round(floatval($_POST['pack_fee']), 2) : 0;
	        $order['card_fee']      = 	isset($_POST['card_fee']) && floatval($_POST['card_fee']) >= 0 ? round(floatval($_POST['card_fee']), 2) : 0;
	
	        $order['money_paid']    = 	$old_order['money_paid'];
	        $order['surplus']       = 	0;
	        //$order['integral']      = 0;
	        $order['integral']		=	intval($_POST['integral']) >= 0 ? intval($_POST['integral']) : 0;
	        $order['integral_money']= 	0;
	        $order['bonus_id']      = 	0;
	        $order['bonus']         = 	0;
	
	        /* 计算待付款金额 */
	        $order['order_amount']  = 	$order['goods_amount'] - $order['discount']
	                                	+ $order['tax']
	                                	+ $order['shipping_fee']
	                                	+ $order['insure_fee']
	                                	+ $order['pay_fee']
	                                	+ $order['pack_fee']
	                                	+ $order['card_fee']
	                                	- $order['money_paid'];
	        if ($order['order_amount'] > 0){
	            if ($old_order['user_id'] > 0){
	                /* 如果选择了红包，先使用红包支付 */
	                if ($_POST['bonus_id'] > 0){
	                    /* todo 检查红包是否可用 */
	                    $order['bonus_id']      = 	$_POST['bonus_id'];
	                    $bonus                  = 	bonus_info($_POST['bonus_id']);
	                    $order['bonus']         = 	$bonus['type_money'];
	
	                    $order['order_amount']  -=	$order['bonus'];
	                }
	
	                /* 使用红包之后待付款金额仍大于0 */
	                if ($order['order_amount'] > 0){
	                    if($old_order['extension_code']!='exchange_goods'){
	                    /* 如果设置了积分，再使用积分支付 */
	                       if (isset($_POST['integral']) && intval($_POST['integral']) > 0){
	                           /* 检查积分是否足够 */
	                           $order['integral']          = intval($_POST['integral']);
	                           $order['integral_money']    = value_of_integral(intval($_POST['integral']));
	                           if ($old_order['integral'] + $user['pay_points'] < $order['integral']){
                                   //sys_msg($_LANG['pay_points_not_enough']);
                                   $this->error(L('pay_points_not_enough'));
                               }	
	                           $order['order_amount'] -= $order['integral_money'];
	                         }
	                    }
	                    else{
	                      if (intval($_POST['integral']) > $user['pay_points']+$old_order['integral']){
	                          //sys_msg($_LANG['pay_points_not_enough']);
	                          $this->error(L('pay_points_not_enough'));
	                      }
	
	                    }
	                    if ($order['order_amount'] > 0){
	                        /* 如果设置了余额，再使用余额支付 */
	                        if (isset($_POST['surplus']) && floatval($_POST['surplus']) >= 0){
	                            /* 检查余额是否足够 */
	                            $order['surplus'] 	= 	round(floatval($_POST['surplus']), 2);
	                            if ($old_order['surplus'] + $user['user_money'] + $user['credit_line'] < $order['surplus']){
	                                //sys_msg($_LANG['user_money_not_enough']);
	                                $this->error(L('user_money_not_enough'));
	                            }
	
	                            /* 如果红包和积分和余额足以支付，把待付款金额改为0，退回部分积分余额 */
	                            $order['order_amount'] 	-= 	$order['surplus'];
	                            if ($order['order_amount'] < 0){
	                                $order['surplus']       += 	$order['order_amount'];
	                                $order['order_amount']  = 	0;
	                            }
	                        }
	                    }
	                    else{
	                        /* 如果红包和积分足以支付，把待付款金额改为0，退回部分积分 */
	                        $order['integral_money']    += 	$order['order_amount'];
	                        $order['integral']          = 	integral_of_value($order['integral_money']);
	                        $order['order_amount']      = 	0;
	                    }
	                }
	                else
	                {
	                    /* 如果红包足以支付，把待付款金额设为0 */
	                    $order['order_amount'] = 0;
	                }
	            }
	        }
	
	        update_order($order_id, $order);
	
	        /* 更新 pay_log */
	        update_pay_log($order_id);
	
	        /* todo 记录日志 */
	        $sn 		= 	$old_order['order_sn'];
	        $new_order 	= 	order_info($order_id);
	        if ($old_order['total_fee'] != $new_order['total_fee']){
	            $sn 	.= 	',' . sprintf($_LANG['order_amount_change'], $old_order['total_fee'], $new_order['total_fee']);
	        }
	        admin_log($sn, 'edit', 'order');
	
	        /* 如果余额、积分、红包有变化，做相应更新 */
	        if ($old_order['user_id'] > 0){
	            $user_money_change 		= 	$old_order['surplus'] - $order['surplus'];
	            if ($user_money_change != 0){
	                log_account_change($user['user_id'], $user_money_change, 0, 0, 0, sprintf($_LANG['change_use_surplus'], $old_order['order_sn']));
	            }
	
	            $pay_points_change 		= 	$old_order['integral'] - $order['integral'];
	            if ($pay_points_change != 0){
	                log_account_change($user['user_id'], 0, 0, 0, $pay_points_change, sprintf($_LANG['change_use_integral'], $old_order['order_sn']));
	            }
	
	            if ($old_order['bonus_id'] != $order['bonus_id']){
	                if ($old_order['bonus_id'] > 0){
	                    $sql 			= 	"UPDATE " . 'ybr_user_bonus' .
	                            			" SET used_time = 0, order_id = 0 " .
	                            			"WHERE bonus_id = '$old_order[bonus_id]' LIMIT 1";
	                    $CommonModel->query($sql);
	                }
	
	                if ($order['bonus_id'] > 0){
	                    $sql 			= 	"UPDATE " . 'ybr_user_bonus' .
	                            			" SET used_time = '" . gmtime() . "', order_id = '$order_id' " .
	                            			"WHERE bonus_id = '$order[bonus_id]' LIMIT 1";
	                    $CommonModel->query($sql);
	                }
	            }
	        }
	
	        if (isset($_POST['finish'])){
	            /* 完成 */
	            if ($step_act == 'add'){
	                /* 订单改为已确认，（已付款） */
	                $arr['order_status'] 	= 	OS_CONFIRMED;
	                $arr['confirm_time'] 	= 	gmtime();
	                if ($order['order_amount'] <= 0){
	                    $arr['pay_status']  = 	PS_PAYED;
	                    $arr['pay_time']    = 	gmtime();
	                }
	                update_order($order_id, $arr);
	            }
	
	            /* 初始化提示信息和链接 */
	            $msgs   	= 	array();
	            $links  	= 	array();
	
	            /* 如果已付款，检查金额是否变动，并执行相应操作 */
	            $order 		= 	order_info($order_id);
	            handle_order_money_change($order, $msgs, $links);
	
	            /* 显示提示信息 */
	            if (!empty($msgs)){
	                //sys_msg(join(chr(13), $msgs), 0, $links);
	                $this->display_message(join(chr(13), $msgs), 0, $links);
	            }
	            else{
	                //ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
	                $this->redirect('/order/order' . '?order_id=' . $order_id);
	                exit;
	            }
	        }
	    }
	    /* 保存发货后的配送方式和发货单号 */
	    elseif ('invoice' == $step){
	        /* 如果不存在实体商品，退出 */
	        if (!exist_real_goods($order_id)){
	            die ('Hacking Attemp');
	        }
	
	        /* 保存订单 */
	        $shipping_id    = 	$_POST['shipping'];
	        $shipping       = 	shipping_info($shipping_id);
	        $invoice_no     = 	trim($_POST['invoice_no']);
	        $invoice_no     = 	str_replace(',', '<br>', $invoice_no);
	        $order 			= 	array(
	            'shipping_id'   => $shipping_id,
	            'shipping_name' => addslashes($shipping['shipping_name']),
	            'invoice_no'    => $invoice_no
	        );
	        update_order($order_id, $order);
	
	        /* todo 记录日志 */
	        $sn = $old_order['order_sn'];
	        admin_log($sn, 'edit', 'order');
	
	        if (isset($_POST['finish'])){
	            //ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
	            $this->redirect("/order/order" . '?order_id=' . $order_id);
	            exit;
	        }
	    }					
		//$this->display();
	}
	
	/**
	 * 处理订单
	 * 
	 */
	public function process(){
	    /* 取得参数 func */
	    $func 			= 	isset($_GET['func']) ? $_GET['func'] : '';
		$CommonModel	=	new CommonModel();
	    /* 删除订单商品 */
	    if ('drop_order_goods' == $func){	
	        /* 取得参数 */
	        $rec_id 	= 	intval($_GET['rec_id']);
	        $step_act 	= 	$_GET['step_act'];
	        $order_id 	= 	intval($_GET['order_id']);
	
	        /* 如果使用库存，且下订单时减库存，则修改库存 */
	        if ($_CFG['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_PLACE){
	             $goods = 	$CommonModel->getRow("SELECT goods_id, goods_number FROM " . 'ybr_order_goods' . " WHERE rec_id = " . $rec_id );
	             $sql 	= 	"UPDATE " . 'ybr_goods' .
	                    	" SET `goods_number` = goods_number + '" . $goods['goods_number'] . "' " .
	                    	" WHERE `goods_id` = '" . $goods['goods_id'] . "' LIMIT 1";
	             $CommonModel->query($sql);
	        }
	
	        /* 删除 */
	        $sql 		= 	"DELETE FROM " . 'ybr_order_goods' . " WHERE rec_id = '$rec_id' LIMIT 1";
	        $CommonModel->query($sql);
	
	        /* 更新商品总金额和订单总金额 */
	        update_order($order_id, array('goods_amount' => order_amount($order_id)));
	        update_order_amount($order_id);
	
	        /* 跳回订单商品 */
	        //ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
	        $this->success('操作成功',U('order/' . $step_act) . '?order_id=' . $order_id . '&step=goods');
	        exit;
	    }	
	    
	    /* 取消刚添加或编辑的订单 */
	    elseif ('cancel_order' == $func){
	        $step_act 	= 	$_GET['step_act'];
	        $order_id 	= 	isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
	        if ($step_act == 'add'){
	            /* 如果是添加，删除订单，返回订单列表 */
	            if ($order_id > 0){
	                $sql = "DELETE FROM " . 'ybr_order_info' . " WHERE order_id = '$order_id' LIMIT 1";
	                $CommonModel->query($sql);
	            }
	            //ecs_header("Location: order.php?act=list\n");
	            $this->success("操作成功",U('order/order_list'));
	            exit;
	        }
	        else{
	            /* 如果是编辑，返回订单信息 */
	            //ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
	            $this->success("操作成功",U('order/order') . '?order_id=' . $order_id);
	            exit;
	        }
	    }
	
	    /* 编辑订单时由于订单已付款且金额减少而退款 */
	    elseif ('refund' == $func){
	        /* 处理退款 */
	        $order_id       = 	$_REQUEST['order_id'];
	        $refund_type    = 	$_REQUEST['refund'];
	        $refund_note    = 	$_REQUEST['refund_note'];
	        $refund_amount  = 	$_REQUEST['refund_amount'];
	        $order          = 	order_info($order_id);
	        order_refund($order, $refund_type, $refund_note, $refund_amount);
	
	        /* 修改应付款金额为0，已付款金额减少 $refund_amount */
	        update_order($order_id, array('order_amount' => 0, 'money_paid' => $order['money_paid'] - $refund_amount));
	
	        /* 返回订单详情 */
	        //ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
	        $this->success('操作成功',U('order/order') . '?order_id=' . $order_id);
	        exit;
	    }	
	    
	    /* 载入退款页面 */
	    elseif ('load_refund' == $func){
	        $refund_amount 	= 	floatval($_REQUEST['refund_amount']);
	        $this->assign('refund_amount', $refund_amount);
	        $this->assign('formated_refund_amount', price_format($refund_amount));
	
	        $anonymous 		= 	$_REQUEST['anonymous'];
	        $this->assign('anonymous', $anonymous); // 是否匿名
	
	        $order_id 		= 	intval($_REQUEST['order_id']);
	        $this->assign('order_id', $order_id); // 订单id
	
	        /* 显示模板 */
	        $this->display('order_refund.htm');
	    }
	
	    else{
	        die('invalid params');
	    }		
	}
	
	
	
	
	
	
}